mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
增加 0583 两个字符串的删除操作 Javascript 方法二
增加 0583 两个字符串的删除操作 Javascript 方法二
This commit is contained in:
@ -228,28 +228,43 @@ func min(a, b int) int {
|
||||
```
|
||||
Javascript:
|
||||
```javascript
|
||||
const minDistance = (word1, word2) => {
|
||||
let dp = Array.from(new Array(word1.length + 1), () => Array(word2.length+1).fill(0));
|
||||
|
||||
for(let i = 1; i <= word1.length; i++) {
|
||||
dp[i][0] = i;
|
||||
// 方法一
|
||||
var minDistance = (word1, word2) => {
|
||||
let dp = Array.from(new Array(word1.length + 1), () =>
|
||||
Array(word2.length + 1).fill(0)
|
||||
);
|
||||
for (let i = 1; i <= word1.length; i++) {
|
||||
dp[i][0] = i;
|
||||
}
|
||||
for (let j = 1; j <= word2.length; j++) {
|
||||
dp[0][j] = j;
|
||||
}
|
||||
for (let i = 1; i <= word1.length; i++) {
|
||||
for (let j = 1; j <= word2.length; j++) {
|
||||
if (word1[i - 1] === word2[j - 1]) {
|
||||
dp[i][j] = dp[i - 1][j - 1];
|
||||
} else {
|
||||
dp[i][j] = Math.min(
|
||||
dp[i - 1][j] + 1,
|
||||
dp[i][j - 1] + 1,
|
||||
dp[i - 1][j - 1] + 2
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[word1.length][word2.length];
|
||||
};
|
||||
|
||||
for(let j = 1; j <= word2.length; j++) {
|
||||
dp[0][j] = j;
|
||||
}
|
||||
|
||||
for(let i = 1; i <= word1.length; i++) {
|
||||
for(let j = 1; j <= word2.length; j++) {
|
||||
if(word1[i-1] === word2[j-1]) {
|
||||
dp[i][j] = dp[i-1][j-1];
|
||||
} else {
|
||||
dp[i][j] = Math.min(dp[i-1][j] + 1, dp[i][j-1] + 1, dp[i-1][j-1] + 2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return dp[word1.length][word2.length];
|
||||
// 方法二
|
||||
var minDistance = function (word1, word2) {
|
||||
let dp = new Array(word1.length + 1)
|
||||
.fill(0)
|
||||
.map((_) => new Array(word2.length + 1).fill(0));
|
||||
for (let i = 1; i <= word1.length; i++)
|
||||
for (let j = 1; j <= word2.length; j++)
|
||||
if (word1[i - 1] === word2[j - 1]) dp[i][j] = dp[i - 1][j - 1] + 1;
|
||||
else dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
|
||||
return word1.length + word2.length - dp[word1.length][word2.length] * 2;
|
||||
};
|
||||
```
|
||||
|
||||
|
Reference in New Issue
Block a user