题目描述
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
示例 1:
输入: ["flower","flow","flight"]
输出: "fl"
示例 2:
输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。
解题思路一
简单朴素,逐一比较就行。
(1)首先可以确定的是最长前缀的长度小于等于列表中最短字符串的长度。
res <= min([len(each) for each in strs]
(2)找到列表中最短字符串,然后以它为标准和其它(包括它自己)列表中的字符串元素进行比较
1、遍历的过程中,如果有一个列表元素没有匹配上,即当前字符不是所有列表字符串元素的前缀,
结束遍历,返回满足条件的前缀。
2、如果当前字符是所有列表字符串元素的前缀,把当前字符加入到前缀中去,遍历下一个字符
3、重复1、2过程,返回满足条件的前缀。
完整代码
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if len(strs) < 1:
return ''
length = [len(each) for each in strs]
idx = length.index(min(length))
template = strs[idx]
res = ''
for i in range(len(template)):
c = template[i]
for index,word in enumerate(strs):
if word[i] != c:
return res
res += c
return res
解题思路二
利用zip、和set。
(1)通过zip操作把列表解析成单字符元组
temp = zip(*(strs))
strs = ['abc','efg','jkl']
temp=['a','b','c'
'e','f','g'
'j','k','l']
实际上是 [('a','e','j'),('b','f','k'),('c','g','l')]
相当于把原来的字符串按列铺开。
(2)通过set操作,判断每个经过zip解析的元组中元素的数目。
if len(set(c)) == 1:
res += c[0]
else:
break
完整代码
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
res = ''
for c in zip(*(strs)):
if len(set(c)) == 1:
res += c[0]
else:
break
return res
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-common-prefix