-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEdit_Distance
46 lines (38 loc) · 1.75 KB
/
Edit_Distance
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
/*
Edit Distance
Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)
You have the following 3 operations permitted on a word:
a) Insert a character
b) Delete a character
c) Replace a character
*/
class Solution {
public:
int minDistance(string word1, string word2) {
int len1=word1.size();
int len2=word2.size();
vector<vector<int> > table(len1+1,(vector<int> (len2+1,0)));
//initialization of table
table[0][0]=0;
for (int i=1; i<len1+1; ++i) table[i][0]=i;
for (int i=1; i<len2+1; ++i) table[0][i]=i;
//optimal function
for (int i=1; i<len1+1; ++i)
for (int j=1; j<len2+1; ++j)
{
table[i][j]=min((word1[i-1]==word2[j-1])?(table[i-1][j-1]):(1+table[i-1][j-1]),min(1+table[i][j-1],1+table[i-1][j]));
}
return table[len1][len2];
}
};
REMARK:
1. So hard. Have no idea.
IDEA:(refer to http://yucoding.blogspot.com/2013/09/leetcode-question-29-edit-distance.html)
"At the first glance, we might think this is a DFS problem, but later on we'll find it is hard to find a quick DFS thought. The problem requires some optimal result (here is the minimum), DP is a good direction to consider."
Actually this is a classic DP problem:
The state is: table[i][j]=minimum number steps convert word1[1:i] to word2[1:j] (here assume string starts from 1).
The optimal function is: table[i+1][j+1] = min [table[i][j]+1 or 0 (+1 if word1[i+1]==word2[j+1], else +0), table[i][j+1]+1, table[i+1][j]+1 ].
Initialization:
table[0][i] = i i=1:|word1| here 0 means "", any string convert to "" needs the length of string
table[j][0] = j i=1:|word2|
table[0][0]=0 "" convert to "" need 0 steps.