[leetcode]python3 算法攻略-最长公共前缀

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

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

方案一:找出最短字符串, 依次验证最短字符串的前n位字符

def longestCommonPrefix(strs):
    """
    :type strs: List[str]
    :rtype: str
    """
    if not strs:
        return ''
    shortest = min(strs, key=len)
    for i, ch in enumerate(shortest):
        for s in strs:
            if s[i] != ch:
                return shortest[: i]
    return shortest

方案二:

class Solution:
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        string = ''
        if strs:
            for i in range(len(strs[0])):
                old_str = string
                string += strs[0][i]
                for j in range(1, len(strs)):
                    if strs[j][: i + 1] != string:
                        return old_str
        return string

你可能感兴趣的:(算法练习)