LeetCode14--最长公共前缀

 1 '''
 2 编写一个函数来查找字符串数组中的最长公共前缀。
 3 如果不存在公共前缀,返回空字符串 ""。
 4 示例 1: 输入: ["flower","flow","flight"] 输出: "fl"
 5 示例 2: 输入: ["dog","racecar","car"] 输出: "" 解释: 输入不存在公共前缀。
 6 '''
 7 
 8 
 9 class Solution:
10     def longestCommonPrefix(self, strs):
11         """
12         :type strs: List[str]
13         :rtype: str
14         """
15         if not len(strs):
16             return ''
17         elif len(strs) == 1:
18             return strs[0]
19         s = ''
20         b = sorted(strs, key=lambda x: len(x))
21         s1 = b[0]
22         for i, v in enumerate(s1):
23             l = []
24             for j in b[1:]:
25                 l.append(v == j[i])
26             if all(l):
27                 s += v
28             else:
29                 break
30         return s
31 
32 
33 if __name__ == '__main__':
34     s = ["flower", "flow", "flight"]
35     ret = Solution().longestCommonPrefix(s)
36     print(ret)

 

posted @ 2018-12-03 14:50  浅尝辄止易初心不改难  Views(117)  Comments(0Edit  收藏  举报