LeetCode 80 Edit Distance

探讨了如何通过最少步骤将一个单词转换为另一个单词,涉及插入、删除和替换操作,利用动态规划解决最优化问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

分析:看到最优化问题先想动规,找到子问题和状体转移方程,那么这个问题就可以用动规解决。

子问题:从word1的前i个字符转移到word2的前j个字符需要的最小步数,用dp[i][j]表示,那么最后答案就是dp[len1][len2].

状态转移方程:

因为有三种转移方式,replace, insert, delete,

如果i,j位置上字符相同,则不需要操作,dp[i+1][j+1] = dp[i][j];

如果不相同,则有三种转移方式:

replace = dp[i][j] + 1;

insert = dp[i][j+1] + 1;

delete = dp[i+1][j] + 1;

dp[i+1][j+1] = min{ replace, insert, delete }.

public class Solution {
    public int minDistance(String word1, String word2) {
        //检查参数
        if(word1==null || word2==null)
            return -1;
        int len1 = word1.length();
        int len2 = word2.length();
        //转移矩阵记录从word1前i个字符到word2前j个字符转换所需要的步数
        int[][] dp = new int[len1+1][len2+1];
        for(int i=0; i<=len1; i++)
            dp[i][0] = i;
        for(int j=0; j<=len2; j++)
            dp[0][j] = j;
        for(int i=0; i<len1; i++){
            char c1 = word1.charAt(i);
            for(int j=0; j<len2; j++){
                char c2 = word2.charAt(j);
                if(c1 == c2)
                    dp[i+1][j+1] = dp[i][j];
                else{
                    int replace = dp[i][j]+1;
                    int insert = dp[i][j+1]+1;
                    int delete = dp[i+1][j]+1;
                    //find the min one
                    int min = Math.min(replace, insert);
                    min = Math.min(min, delete);
                    dp[i+1][j+1] = min;
                }
            }
        }
        return dp[len1][len2];
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值