-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0014_longest_common_prefix.py
More file actions
39 lines (33 loc) · 1.23 KB
/
0014_longest_common_prefix.py
File metadata and controls
39 lines (33 loc) · 1.23 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
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
# Only one word in strs
if (len(strs) == 1):
return strs[0]
# There's empty chracter in strs
if ("" in strs):
return ""
i = 0
prefix = ""
while (i < len(strs) - 1):
# If first letters are different
if (strs[i][0] != strs[i + 1][0]):
return ""
# If prefix doesn't fit
if (prefix != "" and prefix[0] != strs[i][0]):
return ""
if (len(strs[i]) == 1 and len(strs[i + 1]) == 1):
prefix = strs[i][0]
else:
j = 1
if (prefix == ""):
minimum = min(len(strs[i]), len(strs[i + 1]))
else:
minimum = min(len(prefix), len(strs[i]), len(strs[i + 1]))
# Minimum prefix of strs[i][:j] and strs[i + 1][:j]
while (j < minimum + 1):
if (strs[i][:j] != strs[i + 1][:j]):
break
j += 1
prefix = strs[i][:j - 1]
i += 1
return prefix