Created
April 23, 2025 04:54
-
-
Save rjurney/6caef7c0bbaed0425ec42c8995b4f5d5 to your computer and use it in GitHub Desktop.
Find the longest common sub-string among a set of strings...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import defaultdict | |
from pprint import pprint | |
class Solution: | |
def longestCommonPrefix(self, strs: List[str]) -> str: | |
str_count = len(strs) | |
min_len = min([len(s) for s in strs]) | |
print(f"Minimum string length: {min_len:,}") | |
if min_len == 0: | |
return "" | |
print("Indexing strings ...") | |
char_index = defaultdict(int) | |
for i in range(0, min_len): | |
for s in strs: | |
char_index[(i, s[i])] += 1 | |
print(pprint(char_index)) | |
print("Computing maximum prefix from index ...") | |
max_prefixes: list[str] = [] | |
for i, a_str in enumerate(strs): | |
max_prefix = "" | |
for j, c in enumerate(a_str): | |
print(f"Char {i},{j}: {c}") | |
if char_index[(j, c)] != str_count: | |
print(f"Max prefix at end of string '{a_str}': {max_prefix}") | |
break | |
else: | |
print(f"Appending '{c}' to max_prefix '{max_prefix}' to get '{max_prefix + c}'") | |
max_prefix += c | |
max_prefixes.append(max_prefix) | |
return min(max_prefixes) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment