-
Notifications
You must be signed in to change notification settings - Fork 0
/
q14_Longest_Common_Prefix.py
51 lines (48 loc) · 1.18 KB
/
q14_Longest_Common_Prefix.py
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
48
49
50
51
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
ans = ""
n = len(strs)
if n < 1:
return ans
if n == 1:
return strs[0]
i = 0
for i in range(len(strs[0])):
x = strs[0][i]
for j in strs[1:]:
if i >= len(j):
return ans
if x != j[i]:
return ans
ans += x
return ans
def longestCommonPrefix_1(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return ''
for i, chars in enumerate(zip(*strs)):
if len(set(chars)) > 1:
return strs[0][:i]
return min(strs)
def longestCommonPrefix_2(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if len(strs) == 0:
return ''
pre = strs[0]
for st in strs:
while 1:
if st.startswith(pre):
break
else:
pre = pre[:-1]
return pre