Leetcode(14.最长公共前缀)
Python 最长公共前缀
编写函数查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。如下:
输入:strs = ["flower","flow","flight"]
输出:‘fl'
输入:strs = ["dog","racecar","car"]
输出:""
标准答案
Class Solution(object):
def LongestCommonPrefix(self, strs):
result = ""
for i in (zip(*strs)):
s = set(i)
if len(s) ==1:
result += s.pop()
else:
break
return result
细节理解
1.理解zip, zip(*)
lr = ['flow','fleer']
for i in lr:
print(i) #flow, fleer
for u in zip(lr):
print(i) #('flow',), ('fleer',)
for j in list(zip(*lr)):
s=set(j)
print(s) #{
'f'},{
'l'},{
'e', 'o'}.{
'e', 'w'}
if len(s)==1:
print(s) #{
'f'}, {
'l'}
其中i类型为str,u和j类型为tuple,s类型为set.
2.理解 set.pop()
查到的解释是说随机删除元素。但是经过验证几次发现:
对于set内只含str:
删除最后一个元素
对于set内只含int:
删除第一个元素