LeetCode 72. Edit Distance

Posted dacc123

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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];
    
;

以上是关于LeetCode 72. Edit Distance的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode-72.Edit Distance

LeetCode-72-Edit Distance

LeetCode72 Edit Distance

leetcode72. Edit Distance

[leetcode72]Edit Distance

Leetcode 72: Edit Distance