leecode第七十二题(编辑距离)

class Solution {
public:
    int minDistance(string word1, string word2) {
        int len1=word1.size();
        int len2=word2.size();
        
        vector<int> dist(len1+1,0);//用一维矩阵代替二维矩阵,节省空间
        for(int i=0;i<len1+1;i++)//初始化,这一行代表word2含有0个字符,每一个元素代表word1含有i个字符的时候最短编辑距离
            dist[i]=i;
        
        for(int i=1;i<len2+1;i++)
        {
            int temp=dist[0];
            dist[0]=dist[0]+1;
            for(int j=0;j<len1;j++)
            {
                int cur=1;
                if(word1[j]==word2[i-1])
                    cur=0;
                
                int current=dist[j+1];
                dist[j+1]=min(temp+cur,min(dist[j]+1,dist[j+1]+1));//核心,temp+cur代表替换一个字符,dist[j]+1代表删除word1的一个字符,最后那个代表插入和wrod2最后一个一样的字符,取它们里最小
                
                temp=current;              
            }
        }
        
        return dist[len1];                      
    }
};

 分析:

一道非常好的动态规划题,不太容易想,得需要好好理解。

猜你喜欢

转载自www.cnblogs.com/CJT-blog/p/10839795.html