forked from wangzheng0822/algo
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
2a6ae2f
commit 157edb4
Showing
1 changed file
with
31 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
""" | ||
Author: Wenru Dong | ||
""" | ||
|
||
def levenshtein_dp(s: str, t: str) -> int: | ||
m, n = len(s), len(t) | ||
table = [[0] * (n + 1) for _ in range(m + 1)] | ||
table[0] = [j for j in range(m + 1)] | ||
for i in range(m + 1): | ||
table[i][0] = i | ||
for i in range(1, m + 1): | ||
for j in range(1, n + 1): | ||
table[i][j] = min(1 + table[i - 1][j], 1 + table[i][j - 1], int(s[i - 1] != t[j - 1]) + table[i - 1][j - 1]) | ||
return table[-1][-1] | ||
|
||
|
||
def common_substring_dp(s: str, t: str) -> int: | ||
m, n = len(s), len(t) | ||
table = [[0] * (n + 1) for _ in range(m + 1)] | ||
for i in range(1, m + 1): | ||
for j in range(1, n + 1): | ||
table[i][j] = max(table[i - 1][j], table[i][j - 1], int(s[i - 1] == t[j - 1]) + table[i - 1][j - 1]) | ||
return table[-1][-1] | ||
|
||
|
||
if __name__ == "__main__": | ||
s = "mitcmu" | ||
t = "mtacnu" | ||
|
||
print(levenshtein_dp(s, t)) | ||
print(common_substring_dp(s, t)) |