要求:
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string ""
.
解题思路:要一位一位的比较,python中有一个zip(),可以实现一位一位比较
zip()介绍
>>>a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b) # 打包为元组的列表
[(1, 4), (2, 5), (3, 6)]
>>> zip(a,c) # 元素个数与最短的列表一致
[(1, 4), (2, 5), (3, 6)]
>>> zip(*zipped) # 与 zip 相反,*zipped 可理解为解压,返回二维矩阵式
[(1, 2, 3), (4, 5, 6)]
通过以上zip()介绍,通过zip的解压缩方式,可以将传入的strs按照一位一位解压缩成一个一个元组,并于最短的列表一致,比较同一个元组中的元素是不是全部相同,如果不相同则返回相同的部分
代码:
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if len(strs)==0:
return ""
prefix=""
for s in zip(*strs):
if (s[0],)*len(strs)==s:
prefix+=s[0]
else:
break
return prefix