Edit distance - 改进算法待做!

本文详细介绍了一种解决编辑距离问题的经典动态规划算法。该算法通过构建二维数组来追踪两个字符串之间的转换步骤,支持插入、删除及替换操作,并最终计算出将一个字符串转换为另一个字符串所需的最少操作数。

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

典型的DP

1. Array怎么建?

这种有连续感的最值问题就可以直接建array表示到目前为止的最小值,此题中index表示length

涉及两个String,二维

2. changing condition?3种change

3. initial addition?

 改进: -> 空间O(m) 用两个 int[m] 存cur,pre行 (同fibonacci number的改进思想)
           -> lazy DP can be eager: http://www.csse.monash.edu.au/~lloyd/tildeStrings/Alignment/92.IPL.html



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

public class Solution {
    public int minDistance(String word1, String word2) {
        int len1 = word1.length();
        int len2 = word2.length();
        
        int[][] res = new int[len1+1][len2+1];
        
        for (int i = 0; i <= len1; i++) {
            res[i][0] = i;
        }
        
        for(int j = 0; j <= len2; j++) {
            res[0][j] = j;
        }
        
        for (int m = 1; m <= len1; m++) {
            for (int n = 1; n <= len2; n++) {
                 if (word1.charAt(m-1) == word2.charAt(n-1)){
                     res[m][n] =  res[m-1][n-1];             
                 } else {
                     res[m][n] = 1 + getMin(res[m-1][n-1], res[m-1][n], res[m][n-1]);
                 }
            }
        }
        return res[len1][len2];        
    }
    
    public int getMin(int a, int b, int c) {
        return Math.min(a, Math.min(b, c));
    }
     
 }  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值