14.最长公共前缀
题目描述
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。
思路
横向扫描
用 LCP(S1…Sn) 表示字符串 S1…Sn的最长公共前缀。
可以得到以下结论:
LCP(S1…Sn)=LCP(LCP(LCP(S1,S2),S3),…Sn)
基于该结论,可以得到一种查找字符串数组中的最长公共前缀的简单方法。依次遍历字符串数组中的每个字符串,对于每个遍历到的字符串,更新最长公共前缀,当遍历完所有的字符串以后,即可得到字符串数组中的最长公共前缀。
如果在尚未遍历完所有的字符串时,最长公共前缀已经是空串,则最长公共前缀一定是空串,因此不需要继续遍历剩下的字符串,直接返回空串即可。纵向扫描
纵向扫描时,从前往后遍历所有字符串的每一列,比较相同列上的字符是否相同,如果相同则继续对下一列进行比较,如果不相同则当前列不再属于公共前缀,当前列之前的部分为最长公共前缀。代码
class Solution:
def longestCommonPrefix(self, strs) -> str: if not strs: return "" prefix, count = strs[0], len(strs) for i in range(1, count): prefix = self.lcp(prefix, strs[i]) if not prefix: break return prefix def lcp(self, str1, str2): length, index = min(len(str1), len(str2)), 0 while index < length and str1[index] == str2[index]: index += 1 return str1[:index] def longestCommonPrefix1(self, strs) -> 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(1, count): if i == len(strs[j]) or strs[j][i] != c: return strs[0][:i] return strs[0]
if name == “main“:
slt = Solution() # strs = [""] # strs = ["", ""] # strs = ['ab', 'a'] # strs = ["dog", "racecar", "car"] # strs = ['abcd', 'abcf', 'abcde'] strs = ["flower", "flow", "flight"] prefix = slt.longestCommonPrefix1(strs) print("当前{}个字符串的最长公共前缀为:{}".format(len(strs), prefix))