Merge pull request #265 from WayneCui/master

fix levenshtein dist of python version and add JS version
This commit is contained in:
wangzheng0822 2019-03-11 09:58:19 +08:00 committed by GitHub
commit 8eb1cb13f7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 89 additions and 7 deletions

View File

@ -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) );

View File

@ -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]
@ -27,5 +43,17 @@ if __name__ == "__main__":
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))