72. 编辑距离
为保证权益,题目请参考 72. 编辑距离(From LeetCode).
解决方案1
CPP
C++
/*
* LeetCode 72
*/
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
// leetcode 72
class Solution {
public:
static int minDistance(string word1, string word2) {
vector<vector<int> > dp;
for (int i = 0; i <= word1.length(); ++i) {
vector<int> vec_tmp(word2.length() + 1);
dp.push_back(vec_tmp);
}
for (int j = 0; j <= word2.length(); ++j) {
dp[0][j] = j;
}
for (int i = 0; i <= word1.length(); ++i) {
dp[i][0] = i;
}
for (int i = 1; i <= word1.length(); ++i) {
for (int j = 1; j <= word2.length(); ++j) {
if (i - 1 >= 0 && j - 1 >= 0 && word1[i - 1] == word2[j - 1]) {
dp[i][j] = min(dp[i - 1][j] + 1, dp[i][j - 1] + 1);
dp[i][j] = min(dp[i][j], dp[i - 1][j - 1]);
} else {
dp[i][j] = min(dp[i - 1][j] + 1, dp[i][j - 1] + 1);
dp[i][j] = min(dp[i][j], dp[i - 1][j - 1] + 1);
}
}
}
return dp[word1.length()][word2.length()];
}
};
int main() {
Solution so;
cout << so.minDistance("horse", "ros") << endl;
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50