|
1 | 1 | from typing import List |
2 | 2 |
|
3 | 3 |
|
4 | | -def find_longest_common_prefix(strings: List[str]): |
| 4 | +def find_longest_common_prefix(strings: List[str]) -> str: |
5 | 5 | """ |
6 | 6 | find_longest_common_prefix returns the longest string common at the start of any two strings in the passed list. |
7 | 7 |
|
8 | 8 | 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. |
9 | 9 | """ |
| 10 | + |
| 11 | + if not strings or len(strings) < 2: |
| 12 | + return "" |
| 13 | + |
| 14 | + # Precompute sorted strings |
| 15 | + sorted_strings = sorted(strings) |
10 | 16 | longest = "" |
11 | | - for string_index, string in enumerate(strings): |
12 | | - for other_string in strings[string_index+1:]: |
13 | | - common = find_common_prefix(string, other_string) |
14 | | - if len(common) > len(longest): |
15 | | - longest = common |
16 | | - return longest |
17 | 17 |
|
| 18 | + for i in range(len(sorted_strings) - 1): |
| 19 | + s1, s2 = sorted_strings[i], sorted_strings[i + 1] |
| 20 | + # Find common prefix between them |
| 21 | + prefix_len = 0 |
| 22 | + max_len = min(len(s1), len(s2)) |
| 23 | + while prefix_len < max_len and s1[prefix_len] == s2[prefix_len]: |
| 24 | + prefix_len += 1 |
| 25 | + if prefix_len > len(longest): |
| 26 | + longest = s1[:prefix_len] |
18 | 27 |
|
19 | | -def find_common_prefix(left: str, right: str) -> str: |
20 | | - min_length = min(len(left), len(right)) |
21 | | - for i in range(min_length): |
22 | | - if left[i] != right[i]: |
23 | | - return left[:i] |
24 | | - return left[:min_length] |
| 28 | + return longest |
0 commit comments