-
Notifications
You must be signed in to change notification settings - Fork 17
/
longest-common-prefix.py
38 lines (30 loc) · 1.08 KB
/
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
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
result = []
char_index = 0
while len(result) == char_index:
for s in strs:
if len(s) > char_index:
if len(result) <= char_index:
result.append(s[char_index])
else:
if s[char_index] != result[char_index]:
result.pop()
break
else:
if len(result) > char_index:
result.pop()
break
char_index += 1
return ''.join(result)
solution = Solution()
for i in range(1000000):
assert solution.longestCommonPrefix([""]) == ""
assert solution.longestCommonPrefix(["a"]) == "a"
assert solution.longestCommonPrefix(["aa","a"]) == "a"
assert solution.longestCommonPrefix(["flower","flow","flight"]) == "fl"
assert solution.longestCommonPrefix(["dog","racecar","car"]) == ""