Sunday, August 2, 2015

LintCode (119) 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:
  • Insert a character
  • Delete a character
  • Replace a character
Have you met this question in a real interview? 
Yes

Example
Given word1 = "mart" and word2 = "karma", return 3.

首先这是一道dp题目,两个串,干个啥,求最小。
然后要搞清楚三个操作:
插入和删除: f[i-1][j], f[i][j-1] +1
替换: f[i-1][j-1]+1
或者无操作 f[i-1][j-1]
这样就变成了之前的longest subsequence的题目了,
其实你想想就是这样的,longest subsequence不就是找找那些一样的么。。。那么这三种操作完全可以把longest subsequence变成全串儿。。。



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public:    
    /**
     * @param word1 & word2: Two string.
     * @return: The minimum number of steps.
     */
    int minDistance(string word1, string word2) {
        // write your code here
        int m=word1.size();
        int n=word2.size();
        vector< vector<int> > f(m+1, vector<int>(n+1,0));
        for (int i=1; i<=m; i++){
            f[i][0]=i;
        }
        for (int j=1; j<=n; j++){
            f[0][j]=j;
        }
        
        for (int i=1; i<=m; i++){
            for (int j=1; j<=n; j++){
                f[i][j]=min(f[i-1][j],f[i][j-1])+1;
                f[i][j]=min(f[i][j], word1[i-1]==word2[j-1]? f[i-1][j-1]: f[i-1][j-1]+1);
            }
        }
        return f[m][n];
    }
};

No comments:

Post a Comment