编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
示例 1:
输入:strs = ["flower","flow","flight"]
输出:"fl"
示例 2:
输入:strs = ["dog","racecar","car"]
输出:""
解释:输入不存在公共前缀。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-common-prefix
代码:
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if not strs:
return ""
length,count=len(strs[0]),len(strs)
for i in range(length):
c=strs[0][i]
for j in range(count):
if i==len(strs[j]) or c!=strs[j][i] :
return strs[0][:i]
return strs[0]
思路:
线性比较法,第一个字母都进行比较,如果相同则继续比较,不同则直接返回。
其他思路:
递归:
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if not strs:
return ""
if len(strs)==1:
return strs[0]
s=self.lcp(strs[0],strs[1])
if len(strs)==2:
return s
for i in range(2,len(strs)):
s=self.lcp(s,strs[i])
return s
def lcp(self,m,n):
l=min(len(m),len(n))
i=0
while i<l and m[i]==n[i]:
i+=1
return m[:i]
当然还有基于lcp函数的分治算法可以实现
评论区还有一些比较妙的方法,例如根据python中max和min函数,对strs进行遍历寻找,能找到其中最大头序列.
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if not strs: return ""
s1 = min(strs)
s2 = max(strs)
for i,x in enumerate(s1):
if x != s2[i]:
return s2[:i]
return s1