-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path14. Longest Common Prefix.py
More file actions
44 lines (33 loc) · 961 Bytes
/
14. Longest Common Prefix.py
File metadata and controls
44 lines (33 loc) · 961 Bytes
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
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not str:
return ""
for i in range(len(strs[0])):
for string in strs[1:]:
if i >= len(string) or string[i] != strs[0][i]:
return strs[0][:i]
return strs[0]
#法2
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
result =""
i = 0
while True:
try:
sets = set(string[i] for string in strs)
if len(sets) ==1:
result += sets.pop()
i += 1
else:
break
except:
break
return result