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

Solution: Dynamic Programming.
1. Time: O(mn) Space: O(mn)
2. Time: O(mn) Space: O(n);

 1 class Solution {
 2 public:
 3     int minDistance(string word1, string word2) {
 4         int M = word1.size(), N = word2.size();
 5         int dp[M+1][N+1];
 6         for(int i = 0; i < M + 1; i++) {
 7             dp[i][0] = i;
 8         }
 9         for(int j = 0; j < N + 1; j++) {
10             dp[0][j] = j;
11         }
12         for(int i = 1; i < M + 1; i++) {
13             for(int j = 1; j < N + 1; j++) {
14                 if(word1[i-1] == word2[j-1]) {
15                     dp[i][j] = dp[i-1][j-1];
16                 }
17                 else {
18                     dp[i][j] = min(dp[i-1][j-1], min(dp[i][j-1], dp[i-1][j])) + 1;
19                 }
20             }
21         }
22         return dp[M][N];
23     }
24 };

 

posted @ 2014-04-16 05:04  beehard  阅读(133)  评论(0编辑  收藏  举报