LeetCode:14. 最长公共前缀

LeetCode:14. 最长公共前缀

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

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

示例1

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

示例2

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

说明:所有输入只包含小写字母 a-z

LeetCode链接

附代码(Python3):

class Solution:
    def longestCommonPrefix(self, strs):
        if not strs:
            return ''

        max_s, min_s = max(strs), min(strs)    # 最大最小字符串
        
        # 比较最小字符串和最大字符串,不相等时返回
        for pos,ch in enumerate(min_s):
            if ch != max_s[pos]:
                return min_s[:pos]

        return min_s    # 最短字符串全匹配,则返回最短字符串
test = Solution()
strs_li = [["flower","flow","flight"],
            ["dog","racecar","car"],
          ]
for strs in strs_li:
    print(test.longestCommonPrefix(strs))
fl

你可能感兴趣的:(LeetCode)