LeeCode]Edit Distance

来源:互联网 发布:毕业设计node.js 编辑:程序博客网 时间:2024/05/23 16:22

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

经典DP ,引wiki:

      d[i, j] := 最小值(                                d[i-1, j  ] + 1,     // 刪除                                d[i  , j-1] + 1,     // 插入                                d[i-1, j-1] + cost   // 替換
    str1[i] = str2[j]  cost := 0                                否則 cost := 1
)

编程之美上也有详细阐述,算法导论习题。

代码如下:

[cpp] view plaincopy
  1. class Solution {  
  2. public:  
  3.     int minDistance(string word1, string word2) {  
  4.         // Start typing your C/C++ solution below  
  5.         // DO NOT write int main() function  
  6.         int len1 = word1.size();  
  7.         int len2 = word2.size();  
  8.         if(len1==0)  
  9.             return len2;  
  10.         if(len2==0)  
  11.             return len1;  
  12.         vector <vecotr <int> > f(len1+1,vector<int>(len2+1));  
  13.         for(int i = 0 ; i <= len1 ; i++)  
  14.             f[i][0] = i;  
  15.         for(int j =0 ; j <= len2 ; j++)  
  16.             f[0][j] = j;  
  17.         for(int i = 1 ; i<= len1 ; i++)  
  18.             for(int j = 1; j<= len2 ; j++)  
  19.             {  
  20.             int cost = 1;  
  21.             if(word1[i-1]==word2[j-1])  
  22.                 cost =0;  
  23.             f[i][j] = min(f[i-1][j-1]+cost,min(f[i][j-1]+1, f[i-1][j]+1));  
  24.             }  
  25.         return f[len1][len2];  
  26.     }  
  27. };