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

 

相关文章:

  • 2021-08-05
  • 2021-07-13
  • 2021-10-09
  • 2021-10-02
  • 2021-09-30
  • 2022-01-03
猜你喜欢
  • 2021-08-23
  • 2021-11-01
  • 2021-04-30
  • 2021-10-03
  • 2021-06-27
相关资源
相似解决方案