LeetCode--014--最长公共前缀

问题描述:

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

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

示例 1:

输入: ["flower","flow","flight"]
输出: "fl"

示例 2:

输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。

说明:

所有输入只包含小写字母 a-z 。

方法1:

  贪心:将第一个串和第二个串进行比较,得出的最长前缀再与剩下的进行比较。(48ms)

 1 class Solution(object):
 2     def longestCommonPrefix(self, strs):
 3         """
 4         :type strs: List[str]
 5         :rtype: str
 6         """
 7         if len(strs)>1:
 8             
 9             s0 = strs[0]
10             s1 = strs[1]
11         elif len(strs) == 1:
12             return strs[0]
13         else:
14             return ""
15         common = ""
16         flag = True
17         i = 0
18         while flag and i < len(s0) and i < len(s1):
19             if s0[i] == s1[i]:
20                 common += s0[i]
21             else:
22                 flag = False
23             i += 1
24         for i in range (2,len(strs)):
25             c = strs[i]
26             j = 0
27             common2 = ""
28             while j < len(c) and j < len(common):
29                 if c[j] == common[j]:
30                     common2 += c[j]
31                     j += 1
32                 else:
33                     break
34             common = common2
35         return common

方法2(官方)

  利用min和max函数,找出List中最小值元素s1和最大值元素s2,纪录s1中和s2字符不相同时候的下标,进行截断处理。(24ms)

1 if not len(strs):
2   return ''
3 s1 = min(strs)
4 s2 = max(strs)
5 for n, s in enumerate(s1):
6   if not s2[n] == s:
7       return s1[:n]
8 return s1

注:enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。

>>>seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))       # 小标从 1 开始
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
>>>seq = ['one', 'two', 'three']
>>> for i, element in enumerate(seq):
...     print i, element
... 
0 one
1 two
2 three

方法3

1         ans = ""
2         
3         for i in zip(*strs):
4             if  len(set(i)) > 1:
5                 return ans
6             ans += i[0]
7         
8         return ans
9     

strs=["flower","flgdcvghyf","fove"]
for i in zip(*strs):
     print(i)

>>
('f','f','f')
('l','l','o')
('o','g','v')
('w','d','e')

 

 

2018-07-22 11:18:24

posted @ 2018-07-22 11:52  Assange  阅读(282)  评论(0编辑  收藏  举报