Skip to content

Latest commit

 

History

History
65 lines (47 loc) · 1.69 KB

14-longest-common-prefix.md

File metadata and controls

65 lines (47 loc) · 1.69 KB

14. Longest Common Prefix - 最长公共前缀

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

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

示例 1:

输入: ["flower","flow","flight"]
输出: "fl"

示例 2:

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

说明:

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


题目标签:String

题目链接:LeetCode / LeetCode中国

题解

这题很简单,但是容易考虑不周全字符串索引存在性问题。

Language Runtime Memory
python3 52 ms N/A
class Solution:
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        rst = ''
        i = 0
        while True:
            c = []
            for s in strs:
                if len(s) > i:
                    c.append(s[i])
                else:
                    return rst
            c = set(c)
            if len(c) == 1:
                rst += list(c)[0]
                i += 1
            else:
                break
        return rst