Press "Enter" to skip to content

日期: 2022 年 7 月 20 日

14. 最长公共前缀

方法一:

横向扫描
用LCP(S1…Sn)表示字符串S1…Sn的最长公共前缀。

LCP(S_1......S_n) = LCP(LCP(LCP(S_1,S_2),S_3),...S_n)

依次遍历字符串数组中的每个字符串,如果尚未遍历完所以的字符串时,最长公共前缀已经是空字符串,则最长公共前缀一定是空字符串。直接返回空字符串。

Python3 代码解法

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if not strs:
            return ""

        prefix, cont = strs[0], len(strs)
        for i in range(1, cont):
            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]

Source: LeetCode(The title reproduced in this blog is for personal study use only)