zoukankan      html  css  js  c++  java
  • 【LeetCode每天一题】Longest Common Prefix(最长前缀)

    Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".

    Example 1:            Input: ["flower","flow","flight"]                    Output: "fl"

    Example 2:            Input: ["dog","racecar","car"]                     Output: ""                                  Explanation: There is no common prefix among the input strings.

    Note:  All given inputs are in lowercase letters a-z.

    思路


      在看到这道题的时候我选择的是直接进行查找。从第一个字符串中提取出一个字符然后对每一个字符串相应位置进行比较。如果不先等直接返回结果。相等则继续向一下一位查找。时间复杂度为O(s*n)(s为最短字符串的长度, n为列表的长度), 空间复杂度为O(s)。

      第二种办法是使用字典树来解决,但是需要我们先对列表中的字符串进行构造成字典树,最后从字典树的根节点进行查找当有分支的时候就停止。时间复杂度为O(x)(x是列表中所有字符串长度之和), 时间复杂度为O(y)(字典树的大小)。

    图示


    第一种解法图示

             

    第二种解法的图示

                  

    代码


         

     1 class Solution(object):
     2     def longestCommonPrefix(self, strs):
     3         """
     4         :type strs: List[str]
     5         :rtype: str
     6         """
     7         if len(strs) < 2:      # 长度小于2直接返回
     8             return strs[0] if strs else ''
     9         
    10         res_str, min_len = '', len(min(strs))     # 设计结果返回量和最短的字符串长度
    11         i = 0
    12         while i < min_len:                        # 从小标第一个开始
    13             tem = strs[0][i]                       # 取出第一个比较
    14             for j in strs:                        # 从第列表中第一个开始遍历
    15                 if j[i] != tem:                   # 如果不相等直接返回
    16                     return res_str
    17             res_str +=  tem                      
    18             i += 1
    19         return res_str
  • 相关阅读:
    Kubernetes实战(第二版)--第六章 管理Pod容器的生命周期
    Kubernetes实战(第二版)--第五章 在Pods中运行应用程序
    Kubernetes实战(第二版)--第四章 介绍kubernetes API对象
    第三章 部署第一个应用程序
    Kubernetes实战(第二版)----第2章 理解容器
    dfs 例子演示
    Leetcode 135. 分发糖果
    mysql materialized_MySql优化- 执行计划解读与优化(二)
    说说Golang的使用心得
    最详细之教你Jenkins+github自动化部署.Net Core程序到Docker
  • 原文地址:https://www.cnblogs.com/GoodRnne/p/10641402.html
Copyright © 2011-2022 走看看