在刷leetcode的过程中,遇到这道题,现附上我的垃圾代码:
def longestCommonPrefix(strs):
if(len(strs)==0):return ""
shortes=strs[0]
for i in range(len(strs)):
if(len(shortes)>len(strs[i])):
shortes=strs[i]
qianzhui=""
for i in range(len(shortes)):
qianzhui=shortes[:i+1]
for j in range(len(strs)):
if(strs[j].find(qianzhui)!=0):
return qianzhui[:-1]
return qianzhui'''
后面在看评论时看到一个py3的利用ASCII码的巧妙解法,代码如下:
def longestCommonPrefix(self, strs):
if not strs: return ""
s1 = min(strs)
s2 = max(strs)
for i,x in enumerate(s1):
if x != s2[i]:
return s2[:i]
return s1
另外还有一个种看着比较高级的解法,利用了zip
def longestCommonPrefix( strs):
if not strs: return ""
ss = list(map(set, zip(*strs)))
print(ss)
res = ""
for i, x in enumerate(ss):
x = list(x)
if len(x) > 1:
break
res = res + x[0]
return res
实在是高
不懂zip操作的,下面这个例子应该能让你明白:
zip函数
网友评论