【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

 

posted @ 2019-04-02 11:08  GoodRnne  阅读(163)  评论(0编辑  收藏  举报