LeetCode -- 14.最长公共前缀

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 “”。

示例 1:

输入: [“flower”,“flow”,“flight”] 输出: “fl” 示例 2:

输入: [“dog”,“racecar”,“car”] 输出: “” 解释: 输入不存在公共前缀。 说明:

所有输入只包含小写字母 a-z 。

最开始想到的方法是,找到字符串list中,最短的字符串,遍历该字符串判断其他字符串中是否都以这些作为前缀.

    def longestCommonPrefix(self, strs: List[str]) -> str:
        
        if len(strs) == 0:
            return ""

        min_str, min_index = strs[0], 0
        for index, word in enumerate(strs[1:]):
            if len(word) < len(min_str):
                min_str = word
                min_index = index+1
        
        strs[min_index], strs[0] = strs[0], strs[min_index]
        
        res = ''
        for i, c in enumerate(min_str):
            if not all([s[i] == c for s in strs[1:]]):
                break
            res += c
        return res

或者直接用zip(*strs) 来判断


    def longestCommonPrefix(self, strs: List[str]) -> str:
        
        if len(strs) == 0:
            return ""
    

        for i, word in enumerate(zip(*strs)):
            """
            input  a = ['af', 'aa', 'ab']
            for i, word in enumerate(zip(*strs)):
                注意 zip(*strs)相当于从列向量来看, zip(strs) 是从行向量

            0 ('a', 'a', 'a')
            1 ('f', 'a', 'b')

            """
            if len(set(word)) > 1:
                return strs[0][:i]
        else:
            return min(strs)
发布了28 篇原创文章 · 获赞 5 · 访问量 4327

猜你喜欢

转载自blog.csdn.net/m0_37531129/article/details/103450342