zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    child-selector解释
    a:link a:visited a:hover a:active四种伪类选择器的区别
    Java API —— BigDecimal类
    Java API —— BigInteger类
    Java API —— Random类
    Java API —— Math类
    Java API —— Pattern类
    Shuffle和排序
    剖析MapReduce 作业运行机制
    MapReduce编程系列 — 6:多表关联
  • 原文地址:https://www.cnblogs.com/catyuang/p/11109326.html
Copyright © 2011-2022 走看看