Monday, September 7, 2020

583. Delete Operation for Two Strings -----------M ~~~~~~~

 Given two words word1 and word2, find the minimum number of steps required to make word1 and word2 the same, where in each step you can delete one character in either string.

Example 1:

Input: "sea", "eat"
Output: 2
Explanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea".

Note:

  1. The length of given words won't exceed 500.
  2. Characters in given words can only be lower-case letters.


A:

其实就是一个对另一个的 max-common chars

solution: 

每次word2增加一个 character, 都要计算其max common length

 class Solution {

public:
    int minDistance(string word1, string word2) {
        int n1 = word1.length();
        int n2 = word2.length();
        vector<vector<int>> V(n2+1, vector<int>(n1+1,0));
        for(int i = 1;i<= n2;i++){
            char ch2 = word2[i-1];
            for(int j = 1;j<= n1;j++){
                char ch1 = word1[j-1];
                if(ch1==ch2){
                    V[i][j] = 1+V[i-1][j-1]; // this is the max, for sure
                }else{
                    V[i][j] = max(V[i-1][j], V[i][j-1]);// no match, either from above, or from left
                }
            }
        }
        return n1 + n2 - 2* V[n2][n1];
    }
};


这道题的失策在于:

一开始,我想写成row -by-row的扫描。

可是,这个,需要本行和本行上一个没变时的结果。 (而由于需要本行左边的,导致我们不能compute backward) 所以,我们只能用2D array来保存中间结果


还有,就是,没有写出例子来,用笔走一遍,就开始写代码。这样太容易出错了。



No comments:

Post a Comment