-
Notifications
You must be signed in to change notification settings - Fork 0
/
longest-common-prefix.py
41 lines (37 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
39
40
41
from typing import List
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
common_prefix = []
lowest_length = min([len(i) for i in strs])
if len(strs) == 1:
return strs[0]
common_final_idx = -1
for i in range(0, lowest_length):
check_char = strs[0][i]
all_same = True
for s in strs[1:]:
if s[i] != check_char:
all_same = False
break
if all_same:
common_final_idx = i
else:
break
return strs[0][:common_final_idx + 1]
if __name__ == '__main__':
test_cases = [
["flower","flow","flight"],
["dog","racecar","car"],
["ab", "a"],
]
correct_answers = [
"fl",
"",
"a"
]
x = Solution()
for i, t in enumerate(test_cases):
my_answer = x.longestCommonPrefix(t)
print(
f"{'Correct' if my_answer == correct_answers[i] else 'Wrong'} : {my_answer} ({correct_answers[i]})"
)