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

思路:

动规

代码:

 1     int min(int a, int b){
 2         if(a < b)
 3             return a;
 4         return b;
 5     }
 6     int minDistance(string word1, string word2) {
 7         // Note: The Solution object is instantiated only once and is reused by each test case.
 8         int len1 = word1.length(), len2 = word2.length();
 9         if(len1 == 0)
10             return len2;
11         if(len2 == 0)
12             return len1;
13         vector<vector<int> > v(len1+1, vector<int>(len2+1));
14         int i,j;
15         for(i = 1; i <= len1; i++)
16             v[i][0] = i;
17         for(i = 1; i <= len2; i++)
18             v[0][i] = i;
19         for(i = 1; i <= len1; i++){
20             for(j = 1; j <= len2; j++){
21                 if(word1[i-1] == word2[j-1])
22                     v[i][j] = v[i-1][j-1];
23                 else
24                     v[i][j] = min(v[i-1][j-1]+1,min(v[i-1][j]+1, v[i][j-1]+1));
25             }
26         }
27         return v[len1][len2];
28     }

 

posted on 2013-11-03 20:52  waruzhi  阅读(150)  评论(0编辑  收藏  举报

导航