python 练习题 14. 最长公共前缀

地址:https://leetcode-cn.com/problems/longest-common-prefix/

 

 1 '''
 2 编写一个函数来查找字符串数组中的最长公共前缀。
 3 
 4 如果不存在公共前缀,返回空字符串 ""。
 5 
 6  
 7 
 8 示例 1:
 9 
10 输入:strs = ["flower","flow","flight"]
11 输出:"fl"
12 示例 2:
13 
14 输入:strs = ["dog","racecar","car"]
15 输出:""
16 解释:输入不存在公共前缀。
17  
18 
19 提示:
20 
21 1 <= strs.length <= 200
22 0 <= strs[i].length <= 200
23 strs[i] 仅由小写英文字母组成
24 
25 
26 '''
27 '''
28 1.先排序,取最小的数作为匹配的值
29 2.将指标值从大到小取值去匹配,如果全部匹配则跳出循环,返回该公共前缀
30 '''
31 
32 class Solution:
33     def longestCommonPrefix(self, strs: List[str]) -> str:
34         strs.sort(key= lambda i:len(i))
35         s = strs[0]
36         res = ''
37         while len(s) >0:
38             n = 0
39             for i in strs[1:]:
40                 if s != i[:len(s)]:
41                     s = s[:-1]
42                     break
43                 else:
44                     n +=1
45             if n == len(strs[1:]):
46                 res = s
47                 break
48         return res

 

 

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-common-prefix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

posted @ 2022-04-13 20:30  菜小鱼~  阅读(55)  评论(0编辑  收藏  举报