Leetcode 14. Longest Common Prefix

brute force

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if len(strs) == 0:
            return ""
        if len(strs) == 1:
            return strs[0]
        sizes = list(map(len, strs))

        def can(idx):
            for s in strs:
                if s[idx] != strs[0][i]:
                    return False
            return True

        max_ans = min(sizes)
        ans = -1
        for i in range(0, max_ans):
            if not can(i):
                ans = i - 1
                break
            else:
                ans = i
        return strs[0][0:ans + 1] if ans >= 0 else ""

  

原文地址:https://www.cnblogs.com/zywscq/p/10766076.html