美文网首页
14.leetcode题目讲解(Python):最长公共前缀

14.leetcode题目讲解(Python):最长公共前缀

作者: 夏山闻汐 | 来源:发表于2018-09-03 11:44 被阅读165次

    题目如下:

    题目

    解题思路是首先找到最短的那个字符串,因为最长前缀不会超过这个最短字符串的长度。然后将该字符串转换为枚举对象,一旦比对不成功,则返回当前最长的前缀,参考代码如下:

    class Solution:
        def longestCommonPrefix(self, strs):
            """
            :type strs: List[str]
            :rtype: str
            """
            #判断是否为空
            if not strs:
                return ""
    
            # 找到最短的字符串
            shorest = min(strs, key=len)
    
            # 转换为枚举对象
            for i_th, letter in enumerate(shorest):
    
                for other in strs:
    
                    if other[i_th] != letter:
    
                        return shorest[:i_th]
    
            return shortest
    
    

    如果您有更好的解法,欢迎交流
    ps:如果您有好的建议,欢迎交流 :-D,也欢迎访问我的个人博客:tundrazone.com

    相关文章

      网友评论

          本文标题:14.leetcode题目讲解(Python):最长公共前缀

          本文链接:https://www.haomeiwen.com/subject/lpebwftx.html