leetcode14. 最长公共前缀 🌟

题目:

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

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

示例 1:

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

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

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

来源:力扣(LeetCode)
解答:

leetcode优秀方案(来自力扣答案统计页,没有明确作者是谁,可留言告知):

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if len(strs)==0:    return ""
        if len(strs)==1:    return strs[0]
        strs.sort()
        p=""
        for x,y in zip(strs[0],strs[-1]):
            if x==y:
                p+=x
            else:
                break
        return p
View Code
class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if len(strs)==0:
            return ''
        s1=min(strs)
        s2=max(strs)
        for i,v in enumerate(s1):
            if v!=s2[i]:
                return s1[:i]
        return s1
View Code
class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        res = ""
        for i in zip(*strs):
            if len(set(i)) == 1:
                res += i[0]
            else:
                return res
        return res
View Code
class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if len(strs) < 1:
            return ""
        index = 1
        prefix = strs[0]
        while index < len(strs):
            while prefix != strs[index][: len(prefix)]:
                prefix = prefix[:-1]
                if len(prefix) < 1:
                    return ""
            index += 1
        return prefix
View Code
class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        common = ''
        min_length = min([len(i) for i in strs])  if strs else 0
        for i in range(0, min_length):
            letter = set()
            for item in strs:
                letter.add(item[i])
            if len(letter) == 1:
                common += item[i]
            else:
                return common
        return common
View Code
原文地址:https://www.cnblogs.com/catyuang/p/11109326.html