python LeetCode 刷题记录 14

题目 14:

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

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

示例 1:

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

代码:

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        def find_min_len_str(strs):
        # 找到列表中最短的字符串
            if not strs:
                return ""
            shortest = min(strs, key=len)
            return shortest
        
        shortest = find_min_len_str(strs)
        i = len(shortest)
        for s in strs:
            if s != shortest:
                while s[:i] != shortest[:i]:
                    i -= 1
                shortest = shortest[:i]
        return shortest

你可能感兴趣的:(LeetCode,python,leetcode)