Skip to content

Commit 00e3162

Browse files
committed
edit-distance
1 parent c9083b7 commit 00e3162

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,8 @@ Step 2. Add the dependency
4949

5050
<summary>展开查看</summary>
5151

52+
https://leetcode-cn.com/problems/edit-distance/
53+
5254
https://leetcode.cn/problems/count-prefixes-of-a-given-string
5355

5456
https://leetcode.cn/problems/minimum-operations-to-reduce-x-to-zero/

edit-distance/index.ts

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
function minDistance(word1: string, word2: string): number {
2+
const dp: number[][] = Array.from(Array(word1.length + 1), () =>
3+
Array(word2.length + 1).fill(0)
4+
);
5+
6+
for (let i = 1; i <= word1.length; i++) {
7+
dp[i][0] = i;
8+
}
9+
10+
for (let j = 1; j <= word2.length; j++) {
11+
dp[0][j] = j;
12+
}
13+
14+
for (let i = 1; i <= word1.length; i++) {
15+
for (let j = 1; j <= word2.length; j++) {
16+
if (word1[i - 1] === word2[j - 1]) {
17+
dp[i][j] = dp[i - 1][j - 1];
18+
} else {
19+
dp[i][j] = Math.min(
20+
dp[i - 1][j] + 1,
21+
dp[i][j - 1] + 1,
22+
dp[i - 1][j - 1] + 1
23+
);
24+
}
25+
}
26+
}
27+
28+
return dp[word1.length][word2.length];
29+
}
30+
31+
export default minDistance;

0 commit comments

Comments
 (0)