-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path14. Longest Common Prefix.py
More file actions
54 lines (46 loc) · 1.48 KB
/
14. Longest Common Prefix.py
File metadata and controls
54 lines (46 loc) · 1.48 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
48
49
50
51
52
53
54
# solution 1
def longestCommonPrefix(strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return ""
shortest = min(strs, key=len)
for i, ch in enumerate(shortest):
for other in strs:
if other[i] != ch:
return shortest[:i]
# solution 2 Horizontal scanning
# Iterates through the strings[S1, ...Sn], finding
# at each iteration i the longest common prefix of
# string LCP(S1, ...Si) when LCP(S1, ...Si) is an
# empty string, the algorithm ends. Otherwise after
# n iterations, the algorithm returns LCP(S1...Sn)
# Time complexity O(S) where S is the sum of all chars
# in all strings. In the worst case all n strings are the
# same. Space complexity O(1)
def longestCommonPrefix2(strs):
if not strs:
return ""
prefix = strs[0]
for i in range(1, len(strs)):
while strs[i].index != 0:
prefix = prefix[0, len(prefix) - 1]
if not prefix:
return ""
return prefix
# solution 3 vertical scanning
def longestCommonPrefix3(strs):
if not strs:
return ""
for i in range(len(strs[0])):
c = strs[0][i]
for j in range(1, len(strs)):
if i == len(strs[j]) or strs[j][i] != c:
return strs[0][0: i]
return strs[0]
#set str[0] as base
print(longestCommonPrefix3(['flower', 'flow', 'flight']))
print(longestCommonPrefix3(['cathy', 'baathyis', 'athy']))
print(longestCommonPrefix3(['banana', 'bano', 'banary']))