Leetcode——每日一题T14. 最长公共前缀(zip函数法)
法一:正向法(增加字符串)
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if strs ==[]:
return ''
result = ''
a = strs[0]
for temp in strs:
if len(temp) < len(a):
a = temp
for i in range(len(a)):
for j in range(len(strs)):
if a[i] != strs[j][i]:
return result
result += a[i]
return result
法二:逆向法(缩短字符串)
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if strs ==[]:
return ''
a = strs[0]
for i in range(len(strs)):
while strs[i].find(a) != 0:
a = a[:-1]
return a
法三:zip函数法
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if strs ==[]:
return ''
result = ''
for i in zip(*strs):
if len(set(i)) == 1:
result += i[0]
else:
break
return result