-
Notifications
You must be signed in to change notification settings - Fork 0
/
lc_0014_longest_common.py
61 lines (47 loc) · 1.66 KB
/
lc_0014_longest_common.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
"""14. Longest Common Prefix"""
import unittest
from itertools import takewhile, zip_longest
from typing import List
class Solution1:
@staticmethod
def longestCommonPrefix(strs: List[str]) -> str:
return "".join(
s.pop() for s in takewhile(lambda s: len(s) == 1, map(set, zip(*strs)))
)
class Solution2:
@staticmethod
def longestCommonPrefix(strs: List[str]) -> str:
a, b = min(strs), max(strs)
return a[: next((i for i, (x, y) in enumerate(zip(a, b)) if x != y), len(a))]
class Solution3:
@staticmethod
def longestCommonPrefix(strs: List[str]) -> str:
return strs[0][
: next(
(
i
for i, (x, y) in enumerate(zip_longest(min(strs), max(strs)))
if x != y
),
len(strs[0]),
)
]
class MyTestCase(unittest.TestCase):
def setUp(self) -> None:
self.s = [Solution1(), Solution2(), Solution3()]
def test_empty(self):
for s in self.s:
assert s.longestCommonPrefix(["", "dogs"]) == ""
assert s.longestCommonPrefix(["cats", "dogs"]) == ""
def test_example(self):
for s in self.s:
assert s.longestCommonPrefix(["flower", "flow", "flight"]) == "fl"
assert s.longestCommonPrefix(["dog", "racecar", "car"]) == ""
def test_increasing(self):
for s in self.s:
assert s.longestCommonPrefix(["dog", "dogs"]) == "dog"
def test_decreasing(self):
for s in self.s:
assert s.longestCommonPrefix(["ab", "a"]) == "a"
if __name__ == "__main__":
unittest.main()