leetcode14 Longest Common Prefix

 1 """
 2 Write a function to find the longest common prefix string amongst an array of strings.
 3 If there is no common prefix, return an empty string "".
 4 Example 1:
 5 Input: ["flower","flow","flight"]
 6 Output: "fl"
 7 Example 2:
 8 Input: ["dog","racecar","car"]
 9 Output: ""
10 Explanation: There is no common prefix among the input strings.
11 """
12 """
13 本题 提供三种解法,参考资料:https://www.cnblogs.com/davidlidvd/p/12263861.html
14 """
15 """
16 第一种思路是先找到列表中最短字符串的长度,
17 按照这个长度去遍历字符串中的字符,
18 加入到一个不包含重复值的set中,
19 如果set的数目>1,则返回结果,
20 否则就将第一个字符累加返回
21 """
22 class Solution1(object):
23     def longestCommonPrefix(self, strs):
24         if not strs:
25             return ''
26         min_len = len(min(strs))
27         i = 0
28         res = ''
29         while i < min_len:
30             if len(set(map(lambda x:x[i], strs))) > 1: #!!! 基础扎实才能写出
31                 return res      #map()函数接收两个参数,一个是函数,一个是序列
32             else:
33                 res += strs[0][i]
34                 i += 1
35         return res
36 """
37 第二种解法:利用python的zip函数,
38 把str看成list然后把输入看成二维数组,
39 左对齐纵向压缩,然后把每项利用集合去重,
40 之后遍历list中找到元素长度大于1之前的就是公共前缀
41 """
42 class Solution2(object):
43     def longestCommonPrefix(self, strs):
44         if not strs:
45             return ""
46         ss = list(map(set, zip(*strs))) #!!!打包为元组的列表
47         # !!! a = 'flower' b = 'flight'
48         # zipped = zip(a,b)
49         # [('f', 'f'), ('l', 'l'), ('o', 'i'), ('w', 'g'), ('e', 'h'), ('r', 't')]
50         # t = map(set, zipped)
51         # {'f'}, {'l'}, {'o', 'i'}, {'w', 'g'}, {'e', 'h'}, {'r', 't'},
52         #list(t)
53         #[{'f'}, {'l'}, {'o', 'i'}, {'w', 'g'}, {'e', 'h'}, {'r', 't'}]
54         res = ""
55         for i, x in enumerate(ss):
56             x = list(x)         #把map转成list
57             if len(x) > 1:
58                 break
59             res = res + x[0]
60         return res
61 """
62 利用python的max()和min(),
63 在Python里字符串是可以比较的,按照ASCII值排列,
64 举例abb, aba,abac,最大为abb,最小为aba。
65 所以只需要比较最大最小的公共前缀就是整个数组的公共前缀
66 """
67 class Solution3(object):
68     def longestCommonPrefix(self, strs):
69         if not strs:
70             return ""
71         s1 = min(strs)
72         s2 = max(strs)
73         for i,x in enumerate(s1):
74             if x != s2[i]:
75                 return s2[:i]
76         return s1

 

posted @ 2020-02-05 21:49  yawenw  阅读(113)  评论(0编辑  收藏  举报