美文网首页
leetcode 14 python 最长公共前缀

leetcode 14 python 最长公共前缀

作者: 慧鑫coming | 来源:发表于2019-01-31 08:52 被阅读0次

传送门

题目要求

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

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

示例 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

相关文章

网友评论

      本文标题:leetcode 14 python 最长公共前缀

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