【LeetCode每日一题】2020.6.15 14. 最长公共前缀

14. 最长公共前缀

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

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

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

示例:

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

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

分析:

​ 暴力法就可以解决,并且不算复杂。

代码(Python):

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if strs == []:
            return ""
        res = ""
        strs.sort(key=len)
        for index, ch in enumerate(strs[0]):
            for i in range(1, len(strs)):
                if strs[i][index] != ch:
                    return res
            res += ch
        return res
原文地址:https://www.cnblogs.com/enmac/p/13129210.html