[leetcode 14] 最长公共前缀

写一个函数可以查找字符串中的最长公共字符。

示例:

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

输出:"fl"

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

输出:" " (不存在公共的字符串)

代码:

class Solution:
    def longestCommonPrefix(self,strs):
          """
            :type strs: List[str]
            :rtype:  str
          """

            if len(strs) == 0:
              return ""

              prefix=""
              length=1

             while length <= min([len(s) for s in strs]):
                   for i in range(1,len(strs)):
                        if strs[i][:length] != strs[i-1][:length]:
                            return prefix
                   result = strs[0][:length]
                   length +=1
             return prefix
           

原文地址:https://www.cnblogs.com/statlearning2019/p/10341206.html

时间: 2024-08-30 02:44:26

[leetcode 14] 最长公共前缀的相关文章

LeetCode 14. 最长公共前缀(Longest Common Prefix)

14. 最长公共前缀 14. Longest Common Prefix 题目描述 编写一个函数来查找字符串数组中的最长公共前缀. 如果不存在公共前缀,返回空字符串 "". LeetCode14. Longest Common Prefix 示例 1: 输入: ["flower","flow","flight"] 输出: "fl" 示例 2: 输入: ["dog","racec

python(leetcode)-14最长公共前缀

编写一个函数来查找字符串数组中的最长公共前缀. 如果不存在公共前缀,返回空字符串 "". 示例 1: 输入: ["flower","flow","flight"] 输出: "fl" 示例 2: 输入: ["dog","racecar","car"] 输出: "" 解释: 输入不存在公共前缀. 说明: 所有输入只包含小写字母 a-

LeetCode:最长公共前缀【14】

LeetCode:最长公共前缀[14] 题目描述 编写一个函数来查找字符串数组中的最长公共前缀. 如果不存在公共前缀,返回空字符串 "". 示例 1: 输入: ["flower","flow","flight"] 输出: "fl" 示例 2: 输入: ["dog","racecar","car"] 输出: "" 解释: 输入不存

力扣(LeetCode) 14. 最长公共前缀

编写一个函数来查找字符串数组中的最长公共前缀. 如果不存在公共前缀,返回空字符串 "". 示例 1: 输入: ["flower","flow","flight"] 输出: "fl" 示例 2: 输入: ["dog","racecar","car"] 输出: "" 解释: 输入不存在公共前缀. 说明: 所有输入只包含小写字母 a-

【leetcode算法-简单】14. 最长公共前缀

[题目描述] 编写一个函数来查找字符串数组中的最长公共前缀. 如果不存在公共前缀,返回空字符串 "". 示例 1: 输入: ["flower","flow","flight"]输出: "fl" 示例 2: 输入: ["dog","racecar","car"]输出: ""解释: 输入不存在公共前缀.说明: 所有输入只包含小写字母

leetcode 13.最长公共前缀

编写一个函数来查找字符串数组中的最长公共前缀. 如果不存在公共前缀,返回空字符串 "". 1 class Solution: 2 def longestCommonPrefix(self, strs): 3 """ 4 :type strs: List[str] 5 :rtype: str 6 """ 7 if len(strs) == 0: 8 return "" 9 if len(strs) == 1:

LeetCode 7最长公共前缀

编写一个函数来查找字符串数组中的最长公共前缀. 如果不存在公共前缀,返回空字符串 "". 示例 1: 输入: ["flower","flow","flight"] 输出: "fl" 示例 2: 输入: ["dog","racecar","car"] 输出: "" 解释: 输入不存在公共前缀. 说明: 所有输入只包含小写字母 a-

14. 最长公共前缀

编写一个函数来查找字符串数组中的最长公共前缀. 如果不存在公共前缀,返回空字符串 "". 示例 1: 输入: ["flower","flow","flight"] 输出: "fl" 示例 2: 输入: ["dog","racecar","car"] 输出: "" 解释: 输入不存在公共前缀. 说明: 所有输入只包含小写字母 a-

leetcode 14 最长公共子串

原题点这里 水平扫描:依次取每个str的第i个字符,若相同,则公共子串+1,否则结束. public static String longestCommonPrefix(String[] strs) { int strNum = strs.length; if(strNum==1) return strs[0]; int minLen = Integer.MAX_VALUE; for(int i=0;i<strs.length;i++) minLen=Math.min(minLen,strs[i