leetcode-14 最长公共前缀

 编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串 ""。
示例 1:
输入: ["flower","flow","flight"]
输出: "fl"
示例2
输入: ["dog","racecar","car"]
输出: ""

所有输入只包含小写字母 a-z 。

解答:

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """   
        CommonPrefix=''
        if len(strs)==0:
            return CommonPrefix
        elif len(strs)==1:
            return strs[0]   
        else:            
            length=len(strs[0])
            while length>0:
                Prefix=strs[0][:length]
                for i in range(1,len(strs)):
                    if len(strs[i])>=length  and   Prefix == strs[i][:length] :
                        CommonPrefix=Prefix
                    else:
                        CommonPrefix=''
                        break   
                
                if  CommonPrefix=='':
                    length-=1
                else:
                    return CommonPrefix
                
            return CommonPrefix

#a=Solution()
#print  a.longestCommonPrefix(["c","c"])

你可能感兴趣的:(Python)