Skip to content

Commit

Permalink
Merge pull request wangzheng0822#265 from WayneCui/master
Browse files Browse the repository at this point in the history
fix levenshtein dist of python version and add JS version
  • Loading branch information
wangzheng0822 authored Mar 11, 2019
2 parents b98df34 + e085c3b commit 8eb1cb1
Show file tree
Hide file tree
Showing 2 changed files with 89 additions and 7 deletions.
54 changes: 54 additions & 0 deletions javascript/42_dynamic_programming/levenshtein_distance.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
function lsDist(str1, str2) {
var n = str1.length;
var m = str2.length;

var memo = new Array(n);
for(let i = 0; i < n; i++) {
memo[i] = new Array(m);
if (str1[i] === str2[0]) {
memo[i][0] = i - 0;
} else if(i === 0) {
memo[i][0] = 1;
} else {
memo[i][0] = memo[i - 1][0] + 1;
}
}

for(let j = 0; j < m; j++) {
if(str1[0] === str2[j]) {
memo[0][j] = j - 0;
} else if(j === 0) {
memo[0][j] = 1;
} else {
memo[0][j] = memo[0][j - 1] + 1;
}
}

for(let i = 1; i < n; i++) {
for(let j = 1; j < m; j++) {
if(str1[i] === str2[j]) {
memo[i][j] = Math.min(memo[i - 1][j] + 1, memo[i][j - 1] + 1, memo[i - 1][j - 1 ]);
} else {
memo[i][j] = Math.min(memo[i - 1][j] + 1, memo[i][j - 1] + 1, memo[i - 1][j - 1 ] + 1);
}
}
}
console.log(memo);

return memo[n - 1][m - 1];
}


var s = "mitcmu";
var t = "mtacnu";

console.log( lsDist(s, t) );

var s = "kitten";
var t = "sitting";

console.log( lsDist(s, t) );

var s = "flaw";
var t = "lawn";
console.log( lsDist(s, t) );
42 changes: 35 additions & 7 deletions python/42_dynamic_programming/min_edit_dist.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,29 @@

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])
table = [[0] * (n) for _ in range(m)]

for i in range(n):
if s[0] == t[i]:
table[0][i] = i - 0
elif i != 0:
table[0][i] = table[0][i - 1] + 1
else:
table[0][i] = 1

for i in range(m):
if s[i] == t[0]:
table[i][0] = i - 0
elif i != 0:
table[i][0] = table[i - 1][0] + 1
else:
table[i][0] = 1

for i in range(1, m):
for j in range(1, n):
table[i][j] = min(1 + table[i - 1][j], 1 + table[i][j - 1], int(s[i] != t[j]) + table[i - 1][j - 1])

print(table)
return table[-1][-1]


Expand All @@ -27,5 +43,17 @@ def common_substring_dp(s: str, t: str) -> int:
s = "mitcmu"
t = "mtacnu"

print(levenshtein_dp(s, t))
print(common_substring_dp(s, t))

s = "kitten"
t = "sitting"

print(levenshtein_dp(s, t))
print(common_substring_dp(s, t))

s = "flaw"
t = "lawn"

print(levenshtein_dp(s, t))
print(common_substring_dp(s, t))

0 comments on commit 8eb1cb1

Please sign in to comment.