leetcode 14 python 最长公共前缀

传送门

题目要求

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

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

示例 1:
输入: ["flower","flow","flight"]
输出: "fl"

示例 2:
输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。

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

思路一

若列表不为空,取第一个元素,无所谓最长最短,只要出现各元素同索引字符不一致或某一元素耗尽的情况,就中断操作,返回结果

→_→ talk is cheap, show me the code

class Solution:
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if not strs:
            return ""
        result = ""
        for i in range(0, len(strs[0])):
            for j in strs[1:]:
                if i >= len(j) or j[i] != strs[0][i]:
                    return result
            result += strs[0][i]
        return result

思路二

若列表不为空,利用zip拉链函数,将各元素同索引字符组成一个元组,若这个元组中所有元素相同则为公共前缀部分,出现不同,即返回结果

→_→ talk is cheap, show me the code

class Solution:
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if not strs:
            return ""
        result = ""
        for item in zip(*strs):
            if len(set(item)) != 1:
                return result
            result += item[0]
        return result
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容