Skip to content

Commit e1f96a9

Browse files
committed
added 0014_longest_common_prefix.py
1 parent fc9e44a commit e1f96a9

File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
"""
2+
Write a function to find the longest common prefix string amongst an array of strings.
3+
4+
If there is no common prefix, return an empty string "".
5+
6+
Example 1:
7+
Input: strs = ["flower","flow","flight"]
8+
Output: "fl"
9+
10+
Example 2:
11+
Input: strs = ["dog","racecar","car"]
12+
Output: ""
13+
Explanation: There is no common prefix among the input strings.
14+
15+
Constraints:
16+
* 1 <= strs.length <= 200
17+
* 0 <= strs[i].length <= 200
18+
* strs[i] consists of only lower-case English letters.
19+
"""
20+
21+
class Solution:
22+
# O(S) where S is the total number of characters
23+
#def longestCommonPrefix(self, strs: List[str]) -> str:
24+
# prefix = strs[0]
25+
#
26+
# for s in strs[1:]:
27+
# if len(prefix) == 0 or len(s) == 0:
28+
# prefix = ""
29+
# break
30+
31+
# no_change = True
32+
# max_i = min(len(s), len(prefix))
33+
34+
# for i in range(max_i):
35+
# if s[i] != prefix[i]:
36+
# prefix = prefix[:i]
37+
# no_change = False
38+
# break
39+
40+
# if no_change and i == len(s) - 1:
41+
# prefix = s[:i+1]
42+
43+
# return prefix
44+
45+
# O(S) where S is the total number of characters
46+
# Similar to the previous one but using recursion
47+
#def longestCommonPrefix(self, strs: List[str]) -> str:
48+
# if len(strs) == 1:
49+
# return strs[0]
50+
51+
# mid = len(strs) // 2
52+
# prefix = self.longestCommonPrefix(strs[:mid])
53+
# check = self.longestCommonPrefix(strs[mid:])
54+
55+
# if prefix == "" or check == "":
56+
# return ""
57+
58+
# matched = True
59+
# max_i = min(len(prefix), len(check))
60+
# for i in range(max_i):
61+
# if prefix[i] != check[i]:
62+
# prefix = prefix[:i]
63+
# matched = False
64+
# break
65+
66+
# if matched and i == len(check) - 1:
67+
# prefix = check[:i+1]
68+
#
69+
# return prefix
70+
71+
# O(S*log m) Binary-search-like approach
72+
def longestCommonPrefix(self, strs: List[str]) -> str:
73+
r = len(strs[0])
74+
for s in strs[1:]:
75+
r = min(r, len(s))
76+
77+
l = 1
78+
while l <= r:
79+
mid = (l + r) // 2
80+
if self.isShared(strs, mid):
81+
l = mid + 1
82+
else:
83+
r = mid - 1
84+
85+
return strs[0][:(l+r) // 2]
86+
87+
def isShared(self, strs, mid):
88+
prefix = strs[0][:mid]
89+
for s in strs[1:]:
90+
if prefix != s[:mid]:
91+
return False
92+
return True

0 commit comments

Comments
 (0)