LeetCode14 最长公共前缀

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 ""

 1 """
 2 列表前面加星号作用是将列表解开成两个独立的参数,传入函数,
 3 字典前面加两个星号,是将字典解开成独立的元素作为形参。
 4 def add(a, b):
 5     return a+b
 6 
 7 data = [4,3]
 8 print add(*data)
 9 #equals to print add(4, 3)
10 data = {'a' : 4, 'b' : 3}
11 print add(**data)
12 #equals to print add(4, 3)
13 """
14 import re
15 class Solution1:
16     def longestCommonPrefix(self, strs):
17         if len(strs) < 1:
18             return ''
19         prefix = strs[0]
20 
21         for i in range(1, len(strs), 1):
22             while re.match(prefix, strs[i]) is None:
23                 prefix = prefix[0:-1]
24                 if len(prefix) == 0:
25                     return ''
26         return prefix
27 
28 class Solution:
29     def longestCommonPrefix(self, strs):
30         s = ""
31         # print(*strs) # ffa ffc fs
32         # print(zip(*strs))
33         for i in zip(*strs):
34             print(i) # ('f', 'f', 'f')
35             print(set(i))
36             if len(set(i)) == 1:  # ==1说明都相同
37                 s += i[0]
38             else:
39                 break
40         return s
41     
42     
43 if __name__ == '__main__':
44     print(Solution().longestCommonPrefix(['ffa','ffc','fs']))
原文地址:https://www.cnblogs.com/shuangcao/p/13455002.html