Edit Distance

本文详细介绍了如何使用动态规划解决字符串转换问题,通过构建二维数组并运用数学公式进行状态转移,最终计算出将一个字符串转换为另一个字符串所需的最少步骤。文章包括代码实现和关键逻辑解释。

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

这道题目是关于有两个sequence 的dp 题目(最长公共自序列,也为two sequences),这类题目往往需要用一个二维数组,例如 f[ i ][ j ].

i 表示sequence 1 里的某个位置,j stands for sequence2 里的某个位置,然后进行匹配操作。

对于这道题目,重点是理解 function 为什么这么写(网上很多讲解):

num[i][j] = Math.min(Math.min(num[i - 1][j - 1], num[i][j - 1]),num[i - 1][j]) + 1;

public class Solution {
    public int minDistance(String word1, String word2) {
        if (word1 == null && word2 == null) {
            return -1;
        }
        int l1 = word1.length();
        int l2 = word2.length();
        if (l1 == 0) {
            return l2;
        }
        if (l2 == 0) {
            return l1;
        }
        
        int[][] num = new int[l1+1][l2+1];
        for (int i = 0; i <= l1; i++) {
            num[i][0] = i;
        }
        for (int j = 1; j <= l2; j++) {
            num[0][j] = j;
        }
        for (int i = 1; i <= l1; i++) {
            for (int j = 1; j <= l2; j++) {
                if (word1.charAt(i-1) == word2.charAt(j-1)) {
                    num[i][j] = num[i - 1][j - 1];
                } else {
                    num[i][j] = Math.min(Math.min(num[i - 1][j - 1], num[i][j - 1]),num[i - 1][j]) + 1;
                }
            }
        }
        return num[l1 ][l2 ];
        
        
    }
}


注意,当

word1.charAt(i - 1) == word2.charAt(j - 1)

时,当前字符不需要编辑, 直接返回num[i][j]即可

同时,对比第一个代码可以看到,当 word1.length() == 0 或者word2.length()== 0 是不需要拿出来单独考虑的。

public class Solution {
    public int minDistance(String word1, String word2) {
        if (word1 == null || word2 == null) {
            return -1;
        }
        int[][] num = new int[word1.length() + 1][word2.length() + 1];
        num[0][0] = 0;
        for (int i = 1; i <= word2.length(); i++) {
            num[0][i] = i;
        }
        for (int i = 1; i <= word1.length(); i++) {
            num[i][0] = i;
        }
        for (int i = 1; i <= word1.length(); i++) {
            for (int j = 1; j <= word2.length(); j++) {
                if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
                    num[i][j] = num[i - 1][j - 1];
                } else {
                    int delete_insert = Math.min(num[i - 1][j], num[i][j - 1]) ;
                    num[i][j] = Math.min(delete_insert, num[i - 1][j - 1]) + 1;
                }
            }
        }
        return num[word1.length()][word2.length()];
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值