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 class Solution {
 2 public:
 3     int minDistance(string word1, string word2) {
 4         int len1=word1.size();
 5         int len2=word2.size();
 6 
 7         if(len1==0||len2==0) return max(len1,len2);
 8 
 9         vector<vector<int> > f(len1+1,vector<int>(len2+1));
10 
11         for(int i=0;i<=len1;i++) f[i][0]=i;
12         for(int j=0;j<=len2;j++) f[0][j]=j;
13 
14         for(int i=1;i<=len1;i++)
15         {
16             for(int j=1;j<=len2;j++)
17             {
18                 if(word1[i-1]==word2[j-1])
19                     f[i][j]=f[i-1][j-1];
20                 else{
21                     int tmp=min(f[i-1][j],f[i][j-1]);
22                     f[i][j]=min(tmp,f[i-1][j-1])+1;
23                 }
24 
25             }
26         }
27 
28         return f[len1][len2];
29     }
30 };

 

posted on 2015-06-07 10:44  黄瓜小肥皂  阅读(194)  评论(0编辑  收藏  举报