leetcode 72. Edit Distance
Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.
You have the following 3 operations permitted on a word:
Insert a character
Delete a character
Replace a character
Example 1:
Input: word1 = "horse", word2 = "ros"
Output: 3
Explanation:
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')
Example 2:
Input: word1 = "intention", word2 = "execution"
Output: 5
Explanation:
intention -> inention (remove 't')
inention -> enention (replace 'i' with 'e')
enention -> exention (replace 'n' with 'x')
exention -> exection (replace 'n' with 'c')
exection -> execution (insert 'u')
题意:一个字符串,插入,删除,或替换变道另一个字符串,输出最小操作数。
思路:dp.
可以抽象成一个矩阵。
比如下面矩阵表示,比如第1行第3列,表示由空变到ab需要的操作数。第3行第1列表示由ac变到空需要的操作数。
空 a b c
空 0 1 2 3
a 1 0 ?
c 2
c 3
dp[i][j]表示,字符串s的前i个字母变到字符串t的前j个字母需要的最少的操作数。那么dp[i][j] = min(dp[i-1][j-1],dp[i-1][j],dp[i][j-1]) + 1.
分别对应替换,删除,添加。
比如问好位置,可由空->aa替换后一个a,或者a->a添加一个b,或则空->aab删除个a.
class Solution {
public:
int minDistance(string word1, string word2) {
int n = word1.size();
int m = word2.size();
vector<vector<int> > dp(n+1, vector<int>(m+1));
for (int i = 0; i <= n; ++i) {
dp[i][0] = i;
}
for (int j = 0; j <= m; ++j) {
dp[0][j] = j;
}
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
if (word1[i-1] == word2[j-1]) {
dp[i][j] = dp[i-1][j-1];
}
else {
dp[i][j] = min(min(dp[i-1][j], dp[i][j-1]),dp[i-1][j-1])+1;
}
}
}
return dp[n][m];
}
};
原文地址:http://www.cnblogs.com/pk28/
与有肝胆人共事,从无字句处读书。
欢迎关注公众号:
欢迎关注公众号: