LeetCode72编辑代价:一个字符串通过插入、删除、替换变成另一个字符串的代价

这篇博客探讨了如何使用动态规划和递归方法解决LeetCode72问题——计算将一个字符串转换为另一个字符串所需的最小操作数。博主首先介绍了动态规划解决方案,接着讨论了如何通过递归优化时间复杂度,并提供了相关代码示例。
摘要由CSDN通过智能技术生成

这一类的题型有很多,但总的来说思路是一样的。我在这里先给出我们常见的求两个字符串的最长公共序列的,然后逐渐的介绍这道题的三种解法:

Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.

You have the following 3 operations permitted on a word:

  1. Insert a character
  2. Delete a character
  3. Replace a character

 2021年6月23日对他的全新理解

动态规划:

public int minDistance(String word1, String word2) {
        if(word1.length()==0 || word2.length()==0){
            return Math.max(word1.length(),word2.length());
        }
        char[] array1=word1.toCharArray();
        char[] array2=word2.toCharArray();
        int len1=word1.length();
        int len2=word2.length();
        int[][] p=new int[len1][len2]; //从word1的前i个,变道word2的前j个需要的代价;
        //初始化2
        boolean tag=false;
        for(int i=0;i<len1;i++){
            if(array1[i]==array2[0] || tag){
                p[i][0]=i;
                tag=true;
            }else{
                p[i][0]=i+1;
            }

        }
        tag=false;
        for(int j=0;j<len2;j++){
            if(array1[0]==array2[j] || tag){
                p[0][j]=j;
                tag=true;
            }else{
                p[0][j]=j+1;
            }

        }
       //初始化另一种办法
        /*p[0][0]= array1[0]==array2[0] ? 0:1;
        for(int i=1;i<len1;i++){
            p[i][0]= array1[i]==array2[0] ? i:p[i-1][0]+1;

        }
        for(int j=1;j<len2;j++){
            p[0][j]= array1[0]==array2[j] ? j:p[0][j-1]+1;
        }*/


        //状态转化过程1
        for(int i=1;i<len1;i++){
            for(int j=1;j<len2;j++){
                if(array1[i]==array2[j]){
                    p[i][j]=p[i-1][j-1];
                }else{
                    p[i][j]=1+Math.min(p[i][j-1],Math.min(p[i-1][j-1],p[i-1][j]));//加一个,修改,去掉
                }
            }

        }
        return p[len1-1][len2-1];
    }

其次就是进一步压缩空间的办法:

package leetcode;
//压缩空间,因为一直用的是这三个。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值