-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0014_longest_common_prefix.py
More file actions
73 lines (55 loc) · 1.97 KB
/
0014_longest_common_prefix.py
File metadata and controls
73 lines (55 loc) · 1.97 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
'''
14. Longest Common Prefix
Easy
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: strs = ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Constraints:
1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] consists of only lowercase English letters.
'''
from typing import List
class Solution:
def longestCommonPrefix_old(self, strs: List[str]) -> str:
row_count = len(strs)
if row_count == 1:
return strs[0]
position = 0
result = ""
while True:
try:
ch = strs[0][position]
for row in range(row_count-1):
if strs[row+1][position] != ch:
return result
result += ch
position += 1
except Exception:
return result
def longestCommonPrefix(self, strs: List[str]) -> str:
z1 = "".join([x[0] if len(set(x)) == 1 else "-" for x in zip(*strs)])
return z1 if z1.find('-') == -1 else z1[:z1.find('-')]
# print(list(zip(list(x) for x in ["flower","flow","flight"])))
# print()
# z1 = zip([list(x) for x in ["flower", "flow", "flight"]])
# print(list(z1))
strs=["dog", "dog", "dog"]
minimum = min([len(x) for x in strs])
z1 = ''.join([x[0] if len(set(x)) == 1 else "-" for x in zip(*strs)])
print(z1 if z1.find('-') == -1 else z1[:z1.find('-')])
print(z1)
print(z1.find('-'))
print(z1[:z1.find('-')])
sol = Solution()
assert sol.longestCommonPrefix(strs=["flower", "flow", "flight"]) == "fl"
assert sol.longestCommonPrefix(strs=["dog", "racecar", "car"]) == ""
assert sol.longestCommonPrefix(strs=["dog", "", "car"]) == ""
assert sol.longestCommonPrefix(strs=["", "", ""]) == ""
assert sol.longestCommonPrefix(strs=["dog", "dog", "dog"]) == "dog"