1、题目描述
https://leetcode-cn.com/problems/longest-common-prefix/
编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ""。
2、代码详解
使用 zip 根据字符串下标合并成数组,判断合并后数组里元素是否都相同(用set())
zip用法:https://www.runoob.com/python/python-func-zip.html
时间复杂度 O(N) ,N 表示数组中最短字符串长度
空间复杂度 O(1),使用的变量为自然数个
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
# zip(*str) 将 str 中所有字符串并列到迭代器中,逐次并列返回 str 中所有字符串的第 1、2、3、…… 个字符
# list(zip(*["abc","efg","jk"])) --例子输出-→ [('a', 'e', 'j'), ('b', 'f', 'k')] # 加*表示反向zip()
res = ''
for c in zip(*strs):
if len(set(c)) == 1:
res += c[0]
# print(c)
else:
break # 一旦出现第一个不同的字符,提前break
return res
strs = ["flower", "flow", "flight"]
s = Solution()
print(s.longestCommonPrefix(strs))