problem:

Write a function to find the longest common prefix string amongst an array of strings.

最长公共前缀

 

 1 class Solution(object):
 2     def longestCommonPrefix(self, strs):
 3         """
 4         :type strs: List[str]
 5         :rtype: str
 6         """
 7         length = len(strs)
 8         res = ""
 9         if(length==1):
10             return strs[0]
11         for i in range(length-1):
12             j = 0
13             res = ""
14             if(strs[i]==""or strs[i+1]==""):
15                 res = ""
16                 break
17             while(strs[i][j] == strs[i+1][j]):
18                 res+=strs[i][j]
19                 if(j<len(strs[i])-1 and j<len(strs[i+1])-1):
20                     j+=1
21                 else:
22                     break
23             strs[i+1] = res
24         return res

没啥太大问题,只是有两个小坑

input:["这是一个字符串"]

output:"这是一个字符串"

input:[""]或[]

output:""

有多种做法,文中是最简单的一种,还可以建立tire树,有待研究

posted on 2018-01-27 20:55  Qarnet  阅读(107)  评论(0)    收藏  举报