编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。
示例 1:
输入:strs = [“flower”,“flow”,“flight”]
输出:“fl”
示例 2:
输入:strs = [“dog”,“racecar”,“car”]
输出:“”
解释:输入不存在公共前缀。
提示:
1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] 仅由小写英文字母组成
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/longest-common-prefix
通过循环,判断列表里这几个字符串同一个位置的字符是否相同,如果相同作为前缀组成部分,不相同就结束循环并输出前面相同的部分。
判断相同可以用集合的互异性,如果这几个字符相同集合就一个字符,长度为1。
zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象
strs = ["flower","flow","flight"]
s = ""
for i in zip(*strs):
print(i)
然后将这一个个元组转为集合
strs = ["flower","flow","flight"]
s = ""
for i in zip(*strs):
print(i)
n = set(i)
print(n)
集合会将重复的元素去除!
strs = ["flower","flow","flight"]
s = ""
for i in zip(*strs):
print(i)
n = set(i)
print(n)
if len(n) == 1:
s += i[0]
else:
break
print(s)
如果为1就作为前缀。
输出最长公前缀!
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
s = ""
for i in zip(*strs):
print(i)
n = set(i)
print(n)
if len(n) == 1:
s +=i[0]
else:
break
return s
虽然不高,不过也是一种解法!
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
n = list(map(set, zip(*strs)))
s = ""
for m, i in enumerate(n):
i = list(i)
if len(i) == 1:
s +=i[0]
else:
break
return s