LeetCode 最长公共前缀

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 ""

还是自己太菜了,想法是到了,但是编写的过程很痛苦让时间超了。完全可以先找到最短的字符串后,依次以单个去查找每个字符串中对应位置是否是该字符串,否则返回前一个该位置之前的字符串。

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
         #判断是否为空
        if not strs:
            return ""

        # 找到最短的字符串
        shortest = min(strs, key=len)

        # 转换为枚举对象
        for i_th, letter in enumerate(shortest):

            for other in strs:

                if other[i_th] != letter:

                    return shortest[:i_th]

        return shortest

                        
            

应该活用 min() 中还有的key属性,以及enumerate。enumerate以前只是被我用来遍历列表的时候来取 索引值和value的时候用到。才知道还可以直接 对字符串使用,或者说是可以把字符串看成一个列表。

借此,来记下,一直想,一直记录。

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务