mycode   91.59%

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if not strs:
            return ''
        res = ''
        minlen = min([len(s) for s in strs])
        for i in range(minlen):
            alpha = strs[0][i]
            if not all([s[i]==alpha for s in strs[1:]]):
                return res
            res += alpha
        return res

 

参考

思路 : 从后往前逐步缩短搜索的位置

注意:

s = 'asdc'
s[:8] 是可以输出s的,不会报错

class Solution:
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        # initialize common str as the first in list, loop array and shorten it
        if not strs:
            return ""
        prefix = strs[0]
        for s in strs:
            n = len(prefix)
            while n > 0 and prefix[:n] != s[:n]:
                n -= 1
            prefix = s[:n]
        return prefix