LeetCode 72. Edit Distance

题目

简单动态规划

class Solution {
public:
    int dp[1005][1005];
    int minDistance(string word1, string word2) {
        
        int len1=word1.length();
        int len2=word2.length();
        
        if(len1==0)
            return len2;
        if(len2==0)
            return len1;
        
        for(int i=0;i<len1;i++)
        {
            for(int j=0;j<len2;j++)
            {
                dp[i][j]=99999;
                if(i==0&&j==0)
                {
                    if(word1[i]==word2[j])
                    {
                        dp[i][j]=0;
                    }
                    else
                        dp[i][j]=1;
                    
                    continue;
                }
                
                if(i>0)
                    dp[i][j]=min(dp[i][j],dp[i-1][j]+1);
                if(j>0)
                    dp[i][j]=min(dp[i][j],dp[i][j-1]+1);
                if(i>0&&j>0)
                    dp[i][j]=min(dp[i][j],dp[i-1][j-1]+1);
                
                if(word1[i]==word2[j])
                {
                    if(i>0&&j>0)
                        dp[i][j]=min(dp[i][j],dp[i-1][j-1]);
                    if(i==0)
                    {
                        dp[i][j]=min(dp[i][j],j);
                    }
                    if(j==0)
                        dp[i][j]=min(dp[i][j],i);
                }
                
            }
        }
        
        return dp[len1-1][len2-1];
    }
};
posted @ 2019-10-03 08:14  Shendu.CC  阅读(172)  评论(0编辑  收藏  举报