zoukankan      html  css  js  c++  java
  • LeetCode-14. 最长公共前缀

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

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

    示例 1:

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

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

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

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

    方法一:

     1 class Solution:
     2     def longestCommonPrefix(self, strs: List[str]) -> str:
     3         result = ""
     4         i = 0
     5         while True:
     6             try:
     7                 #使用set方法,查找第 i 个位置不同的字母有多少个 
     8                 sets = set(item[i] for item in strs )
     9                 #如果个数为 1 则并入到 result 中,并从set中删除保留的哪一个数据
    10                 if len(sets) == 1:
    11                     result += sets.pop()
    12                     i += 1
    13                 else:break
    14             except Exception:
    15                 break
    16         return result

    方法二:

    1 class Solution:     #查找最大公共前缀
    2     def longestCommonPrefix(self, strs):
    3         if not strs:
    4             return ""
    5         for i in range(len(strs[0])):
    6             for item in strs[1:]:
    7                 if i >= len(item) or item[i] != strs[0][i]:
    8                     return strs[0][:i]
    9         return ""



    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/longest-common-prefix

  • 相关阅读:
    [MetaHook] Quake FMOD player demo
    [MetaHook] Quake FMOD function
    [MetaHook] Load TGA texture to OpenGL
    [MetaHook] R_RicochetSprite
    [MetaHook] R_SparkStreaks
    [MetaHook] R_SparkEffect
    [MetaHook] R_SparkShower
    [MetaHook] Load large texture from model
    [MetaHook] Quake Bink function
    变量命名规范
  • 原文地址:https://www.cnblogs.com/Halo-zyh-Go/p/12308104.html
Copyright © 2011-2022 走看看