zoukankan      html  css  js  c++  java
  • 72. Edit Distance (String; DP)

    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

    思路:动态规划。将所要求的min step作为状态,dp[i][j]表示word2的前j各字符通过word1的前i各字符转换最少需要多少步。可以看到有两个以上的string,通常状态要定义为二维数组,表示两个字符串前几个字符之间的关系。

    class Solution {
    public:
        int minDistance(string word1, string word2) {
            if(word1.length()==0) return word2.length();
            if(word2.length()==0) return word1.length();
            
            vector<vector<int>> dp(word1.length(), vector<int>(word2.length(),0));
            
            if(word1[0]==word2[0]) dp[0][0] = 0;
            else dp[0][0] = 1;
           
            for(int i = 0; i < word1.length(); i++){
                for(int j = 0; j < word2.length(); j++){
                    if(i>0 && j>0){
                        if(word1[i]==word2[j]){
                            dp[i][j] =min(min(dp[i-1][j], dp[i][j-1])+1,dp[i-1][j-1]);
                        }
                        else{
                            dp[i][j]=min(min(dp[i-1][j], dp[i][j-1]),dp[i-1][j-1])+1;
                        }
                    }
                    else if(i>0){ 
                        if(word1[i]==word2[j]){
                            dp[i][j] =i;
                        }
                        else{
                            dp[i][j]=dp[i-1][j]+1;
                        }
                    }
                    else if(j>0){
                        if(word1[i]==word2[j]){
                            dp[i][j] =j;
                        }
                        else{
                            dp[i][j]=dp[i][j-1]+1;
                        }
                    }
                }
            }
            
            return dp[word1.length()-1][word2.length()-1];
        }
    };
  • 相关阅读:
    cf 1452E. Two Editorials(中点排序)
    cf 888G
    cf 1447E. Xor Tree(二进制分治)
    2020ICPC·小米 网络选拔赛第一场 E-Phone Network (线段树)
    cf 1447D. Catching Cheaters ( 最大子段和思想 dp )
    POJ
    cf 1437F.Emotional Fishermen(计数dp)
    霍夫丁不等式
    切比雪夫不等式
    霍夫丁不等式引理证明
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4920976.html
Copyright © 2011-2022 走看看