Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 76bd067

Browse files
dp: edit distance
1 parent c6ca386 commit 76bd067

File tree

1 file changed

+100
-0
lines changed

1 file changed

+100
-0
lines changed

‎cpp/leetcode/72.编辑距离.cpp

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
/*
2+
* @lc app=leetcode.cn id=72 lang=cpp
3+
*
4+
* [72] 编辑距离
5+
*
6+
* https://leetcode.cn/problems/edit-distance/description/
7+
*
8+
* algorithms
9+
* Hard (62.79%)
10+
* Likes: 2979
11+
* Dislikes: 0
12+
* Total Accepted: 369.4K
13+
* Total Submissions: 588.3K
14+
* Testcase Example: '"horse"\n"ros"'
15+
*
16+
* 给你两个单词 word1 和 word2, 请返回将 word1 转换成 word2 所使用的最少操作数
17+
* 。
18+
*
19+
* 你可以对一个单词进行如下三种操作:
20+
*
21+
*
22+
* 插入一个字符
23+
* 删除一个字符
24+
* 替换一个字符
25+
*
26+
*
27+
*
28+
*
29+
* 示例 1:
30+
*
31+
*
32+
* 输入:word1 = "horse", word2 = "ros"
33+
* 输出:3
34+
* 解释:
35+
* horse -> rorse (将 'h' 替换为 'r')
36+
* rorse -> rose (删除 'r')
37+
* rose -> ros (删除 'e')
38+
*
39+
*
40+
* 示例 2:
41+
*
42+
*
43+
* 输入:word1 = "intention", word2 = "execution"
44+
* 输出:5
45+
* 解释:
46+
* intention -> inention (删除 't')
47+
* inention -> enention (将 'i' 替换为 'e')
48+
* enention -> exention (将 'n' 替换为 'x')
49+
* exention -> exection (将 'n' 替换为 'c')
50+
* exection -> execution (插入 'u')
51+
*
52+
*
53+
*
54+
*
55+
* 提示:
56+
*
57+
*
58+
* 0 <= word1.length, word2.length <= 500
59+
* word1 和 word2 由小写英文字母组成
60+
*
61+
*
62+
*/
63+
64+
#include <string>
65+
#include <vector>
66+
using namespace std;
67+
68+
// @lc code=start
69+
class Solution {
70+
public:
71+
// dp[i][j]表示s的前i个字符与t的前j个字符的编辑距离
72+
// 当s[i]==t[j]时,dp[i][j] = dp[i-1][j-1]
73+
// 当s[i]!=t[j]时,dp[i][j] = min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1])+1
74+
// 其中dp[i-1][j-1] 表示替换操作,dp[i-1][j] 表示删除操作,dp[i][j-1]
75+
// 表示插入操作
76+
int minDistance(string word1, string word2) {
77+
int m = word1.size(), n = word2.size();
78+
if (m * n == 0) {
79+
return m + n;
80+
}
81+
vector<vector<int>> dp(m + 1, vector<int>(n + 1));
82+
for (int i = 0; i <= m; i++) {
83+
dp[i][0] = i;
84+
}
85+
for (int i = 0; i <= n; i++) {
86+
dp[0][i] = i;
87+
}
88+
for (int i = 1; i <= m; i++) {
89+
for (int j = 1; j <= n; j++) {
90+
if (word1[i - 1] == word2[j - 1]) {
91+
dp[i][j] = dp[i - 1][j - 1];
92+
} else {
93+
dp[i][j] = min(dp[i - 1][j - 1], min(dp[i - 1][j], dp[i][j - 1])) + 1;
94+
}
95+
}
96+
}
97+
return dp[m][n];
98+
}
99+
};
100+
// @lc code=end

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /