Skip to content

Commit d8dfc28

Browse files
Update longest_common_substring.py
1 parent 53b1b10 commit d8dfc28

1 file changed

Lines changed: 10 additions & 6 deletions

File tree

dynamic_programming/longest_common_substring.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -46,16 +46,20 @@ def longest_common_substring(text1: str, text2: str) -> str:
4646
if not text1 or not text2:
4747
return ""
4848

49-
dp = [[0] * (len(text2) + 1) for _ in range(len(text1) + 1)]
50-
max_length, end_pos = 0, 0
49+
text1_length = len(text1)
50+
text2_length = len(text2)
51+
52+
dp = [[0] * (text2_length + 1) for _ in range(text1_length + 1)]
53+
end_pos = 0
54+
max_length = 0
5155

52-
for i in range(1, len(text1) + 1):
53-
for j in range(1, len(text2) + 1):
56+
for i in range(1, text1_length + 1):
57+
for j in range(1, text2_length + 1):
5458
if text1[i - 1] == text2[j - 1]:
55-
dp[i][j] = dp[i - 1][j - 1] + 1
59+
dp[i][j] = 1 + dp[i - 1][j - 1]
5660
if dp[i][j] > max_length:
57-
max_length = dp[i][j]
5861
end_pos = i
62+
max_length = dp[i][j]
5963

6064
return text1[end_pos - max_length : end_pos]
6165

0 commit comments

Comments
 (0)