-
-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathcommon_prefix.py
More file actions
31 lines (22 loc) · 949 Bytes
/
common_prefix.py
File metadata and controls
31 lines (22 loc) · 949 Bytes
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
from typing import List
def find_longest_common_prefix(strings: List[str]):
"""
find_longest_common_prefix returns the longest string common at the start of any two strings in the passed list.
In the event that an empty list, a list containing one string, or a list of strings with no common prefixes is passed, the empty string will be returned.
"""
if not strings or len(strings) < 2:
return ""
# Precompute sorted strings
sorted_strings = sorted(strings)
longest = ""
for i in range(len(sorted_strings) - 1):
common = find_common_prefix(sorted_strings[i], sorted_strings[i + 1])
if len(common) > len(longest):
longest = common
return longest
def find_common_prefix(left: str, right: str) -> str:
min_length = min(len(left), len(right))
for i in range(min_length):
if left[i] != right[i]:
return left[:i]
return left[:min_length]