Skip to content

Commit a19259d

Browse files
authored
Update longest_common_substring.py
- Combined the ans_index and ans_length into a single tuple to track the best match (position + length) more cleanly. - Early exit for empty strings.
1 parent 0a3a965 commit a19259d

1 file changed

Lines changed: 11 additions & 12 deletions

File tree

dynamic_programming/longest_common_substring.py

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -43,22 +43,21 @@ def longest_common_substring(text1: str, text2: str) -> str:
4343
if not (isinstance(text1, str) and isinstance(text2, str)):
4444
raise ValueError("longest_common_substring() takes two strings for inputs")
4545

46-
text1_length = len(text1)
47-
text2_length = len(text2)
46+
if not text1 or not text2:
47+
return ''
4848

49-
dp = [[0] * (text2_length + 1) for _ in range(text1_length + 1)]
50-
ans_index = 0
51-
ans_length = 0
49+
dp = [[0] * (len(text2) + 1) for _ in range(len(text1) + 1)]
50+
max_length, end_pos = 0, 0
5251

53-
for i in range(1, text1_length + 1):
54-
for j in range(1, text2_length + 1):
52+
for i in range(1, len(text1) + 1):
53+
for j in range(1, len(text2) + 1):
5554
if text1[i - 1] == text2[j - 1]:
56-
dp[i][j] = 1 + dp[i - 1][j - 1]
57-
if dp[i][j] > ans_length:
58-
ans_index = i
59-
ans_length = dp[i][j]
55+
dp[i][j] = dp[i - 1][j - 1] + 1
56+
if dp[i][j] > max_length:
57+
max_length = dp[i][j]
58+
end_pos = i
6059

61-
return text1[ans_index - ans_length : ans_index]
60+
return text1[end_pos - max_length:end_pos]
6261

6362

6463
if __name__ == "__main__":

0 commit comments

Comments
 (0)