美文网首页
LeetCode-14 最长公共前缀

LeetCode-14 最长公共前缀

作者: FlyCharles | 来源:发表于2019-02-19 23:23 被阅读0次

题目

https://leetcode-cn.com/problems/longest-common-prefix/

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

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

示例 1:

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

示例 2:

输入: ["dog","racecar","car"]
输出: ""

解释: 输入不存在公共前缀。

说明:

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


我的AC

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if len(strs) == 0:
            return ""
        min_len = min([len(str) for str in strs])
        idx = 0
        while idx < min_len:
            Iscom = True
            for i in range(len(strs)-1):
                if strs[i][idx] != strs[i+1][idx]:
                    Iscom = False
                    break
            if Iscom:
                idx = idx + 1
            else:
                break
        return strs[0][:idx]    

28 ms 7.1 MB


小结

  1. 输入的列表有可能为空,可能需要再最开始进行判断
if len(list) == 0:
# or
if not list == 0:
  1. 列表的元素可能为空
  2. 列表的元素可能相等

相关文章

网友评论

      本文标题:LeetCode-14 最长公共前缀

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