关于Leetcode中求最长公共前缀的答案,
其中有一个答案是
Python 特性,取每一个单词的同一位置的字母,看是否相同。
```Python []
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
res = ""
for tmp in zip(*strs):
tmp_set = set(tmp)
if len(tmp_set) == 1:
res += tmp[0]
else:
break
return res
起初并不理解其中zip(*strs)的做法到底什么意思,后来看了
https://blog.youkuaiyun.com/weixin_41599977/article/details/89386629
对于*的讲解
将zip(*)其中的类比为了传参时候的可变数量的传参.感觉豁然开朗,
strs=[“flower”,“flow”,“flight”]
所以 zip(*strs) -> zip(“flower”,“flow”,“flight”)
a = ['f','l','o','w','e','r']
b = ['f','l','o','w']
c = ['f','l','i','g','h','t']
此时zip("flower","flow","flight") ->zip(a,b,c)
此时结果为
然后再对tmp_set进行判断长度,长度为1,则表明这个位置的字母相同
如此就可以得到最终的结果了