14. 最长公共前缀-----leetcode刷题(python解题)

[TOC]python

题目

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

若是不存在公共前缀,返回空字符串 ""。数组

示例 1:网络

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

示例 2:app

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

解释: 输入不存在公共前缀。
说明:函数

全部输入只包含小写字母 a-z 。code

来源:力扣(LeetCode)
连接:https://leetcode-cn.com/probl...
著做权归领扣网络全部。商业转载请联系官方受权,非商业转载请注明出处。内存

解答

先找到最短字符串的长度,这样能减小循环次数而后在进行循环找到公共前缀leetcode

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        a= 0
        num = []
        len_strs = len(strs)
        for i in strs:
            num.append(len(i))
        if num ==[]:
            return ""
        min_num = min(num)
        for i in range(min_num):
            for j in range(len_strs-1):
                
                if strs[j][i] != strs[j+1][i]:
                    break
            else:
                a +=1
                continue
            break
        return strs[0][:a]

执行效果

  • 执行结果:经过
  • 执行用时 :28 ms, 在全部 Python 提交中击败了79.27%的用户
  • 内存消耗 :12 MB, 在全部 Python 提交中击败了16.85%的用户
相关文章
相关标签/搜索