-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathquestion_9.py
More file actions
47 lines (40 loc) · 1.04 KB
/
question_9.py
File metadata and controls
47 lines (40 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#!/usr/bin/env python
# @Time : 2018/5/5 下午1:03
# @Author : cancan
# @File : question_9.py
# @Function : 最长公共前缀
"""
Question:
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
Example 1:
输入: ["flower","flow","flight"]
输出: "fl"
Example 2:
输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。
Note:
所有输入只包含小写字母 a-z 。
"""
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
t = min(strs, key=lambda x: len(x)) if strs else ''
l = len(t)
for i in strs:
if t == i:
continue
for y in range(l):
if t[:y+1] != i[:y+1]:
t = '' if y == 0 else t[:y]
break
return t
if __name__ == "__main__":
a = Solution()
# s = ["flower","flow","flight"]
s = ["ca","a"]
print(a.longestCommonPrefix(s))