每天一道leetecode:14、最长公共前缀(easy)
程序员文章站
2022-07-14 07:57:54
...
这道题,首先找第一个字符串作为现在的字符串,然后不断遍历其余字符串,找出最长匹配的前缀,并不断更新现在的字符串,最后得到的现在的字符串就是最长公共前缀。
很简单。
def longestCommonPrefix(strs):
if len(strs) == 0:
return ''
s = strs[0]
for i in range(len(strs)):
if i == 0:
continue
str = ''
s_ = strs[i]
if len(s) > len(s_):
len_s = len(s_)
else:
len_s = len(s)
#print(s,s_,len_s)
for m in range(len_s):
if s[m] == s_[m]:
str += s[m]
#print(str)
else:
s = str
break
s = str
return s
s = []
s.append('flower')
s.append('flow')
s.append('flight')
print(longestCommonPrefix(s))
s1 = []
s1.append('dog')
s1.append('racecar')
s1.append('car')
print(longestCommonPrefix(s1))
s2 = []
print(longestCommonPrefix(s2))