【leetode 14】最长公共前缀

方法1:

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if not strs: return ""
        ans = strs[0]
        i = 1
        while i < len(strs):
            while strs[i].find(ans)!=0:
                ans = ans[:len(ans)-1]
            i+=1
        return ans

方法2:

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        ans = ''
        for item in zip(*strs):
            tmp = set(item)
            if len(tmp)==1:
                ans+=item[0]
            else:
                return ans
        return ans
上一篇:Task03——采用C++


下一篇:14. 最长公共前缀 (leetcode)