583. Delete Operation for Two Strings

Posted stAr_1

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了583. Delete Operation for Two Strings相关的知识,希望对你有一定的参考价值。

这个题中有个方法是求两个字符串的最大公共子串的长度,动态规划,一定记住:根据当前位置两个字符是不是相同,做不同的处理。

/*
        两个字符串,每次只能删除一个字符,求多少步可以让两个字符串相同,其实就是两个字符串的最大公共子序列长度。
        重要,要记住,用动态规划,dp[i][j]代表第一个字符前i个字符和第二个字符前j个字符的最大公共子序列长度是多少
        dp[i][j] = (word1[i]==word2[j])?dp[i-1][j-1]+1:Math.max(dp[i][j-1],dp[i-1][j])
         */
        int l1 =word1.length();
        int l2 = word2.length();
        int[][] dp = new int[l1+1][l2+1];
        for (int i = 1; i < l1+1; i++) {
            for (int j = 1; j < l2+1; j++) {
                //注意这里由于第一个字符需要前边的,所以dp数组多了一个空,所以下标不对应了,动态规划数组一定要考虑
                //数组下标和数据下标是不是对应。
                dp[i][j] = (word1.charAt(i-1)==word2.charAt(j-1))?dp[i-1][j-1]+1:Math.max(dp[i][j-1],dp[i-1][j]);
            }
        }
        return l1+l2-2*dp[l1][l2];

 

以上是关于583. Delete Operation for Two Strings的主要内容,如果未能解决你的问题,请参考以下文章

583. Delete Operation for Two Strings

583. Delete Operation for Two Strings

[leetcode-583-Delete Operation for Two Strings]

[LeetCode] 583. Delete Operation for Two Strings

583. Delete Operation for Two Strings

[LeetCode] 583. Delete Operation for Two Strings 两个字符串的删除操作