[Leetcode 93] 72 Edit Distance

Problem:

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

 

Analysis:

This is the classic dynamic programming problem. With the following inductive formula, it's easy to solve this problem:

D(i, j) = min{D(i-1, j)+1, D(i, j-1)+1, D(i-1, j-1)+replace_cost}, replace_cost = 1 if word[i] != word[j] else euqals 0. Remember here the 1 can be changed to any other proper value.

What the formula is saying is that: a new state can be obtained by 1). delete a character from string A; 2). insert a character into string B; 3). replace a character in string A to string B.

 

Code:

 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.length()+1, len2 = word2.length()+1;
 7         int way[len1][len2];
 8         
 9         for (int i=0; i<len1; i++)
10             way[i][0] = i;
11         
12         for (int j=0; j<len2; j++)
13             way[0][j] = j;
14         
15         int rep;
16         for (int i=1; i<len1; i++)
17             for (int j=1; j<len2; j++) {
18                 way[i][j] = min(way[i-1][j]+1, way[i][j-1]+1);
19                 rep = (word1[i-1] == word2[j-1]) ? 0 : 1;
20                 way[i][j] = min(way[i][j], way[i-1][j-1]+rep);
21             }
22         
23         
24         return way[len1-1][len2-1];
25     }
26 };
View Code

posted on 2013-07-28 11:00  freeneng  阅读(179)  评论(0编辑  收藏  举报

导航