资讯专栏INFORMATION COLUMN

[LintCode/LeetCode] Edit Distance

snowell / 2875人阅读

摘要:构造数组,是的,是的,是将位的转换成位的需要的步数。初始化和为到它们各自的距离,然后两次循环和即可。

Problem

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:

Insert a character
Delete a character
Replace a character

Example

Given word1 = "mart" and word2 = "karma", return 3.

Note

构造dp[i][j]数组,iword1index+1jword2index+1dp[i][j]是将i位的word1转换成j位的word2需要的步数。初始化dp[i][0]dp[0][i]dp[0][0]到它们各自的距离i,然后两次循环ij即可。
理解三种操作:insertion是完成i-->j-1之后,再插入一位才完成i-->jdeletion是完成i-->j之后,发现i多了一位,所以i-1-->j才是所求,需要再删除一位才完成i-->j;而replacement则是换掉word1的最后一位,即之前的i-1-->j-1已经完成,如果word1的第i-1位和word2的第j-1位相等,则不需要替换操作,否则要替换一次完成i-->j

Solution
public class Solution {
    public int minDistance(String word1, String word2) {
        int m = word1.length(), n = word2.length();
        int[][] dp = new int[m+1][n+1];
        for (int i = 0; i <= m; i++) {
            for (int j = 0; j <= n; j++) {
                if (i == 0) dp[i][j] = j;
                else if (j == 0) dp[i][j] = i;
                else {
                    int insert = dp[i][j-1] + 1;
                    int delete = dp[i-1][j] + 1;
                    int replace = dp[i-1][j-1] + (word1.charAt(i-1) == word2.charAt(j-1) ? 0 : 1);
                    dp[i][j] = Math.min(insert, Math.min(delete, replace));
                }
            }
        }
        return dp[m][n];
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/65798.html

相关文章

  • [LintCode/LeetCode] Best Meeting Point

    Problem A group of two or more people wants to meet and minimize the total travel distance. You are given a 2D grid of values 0 or 1, where each 1 marks the home of someone in the group. The distance ...

    morgan 评论0 收藏0
  • [LintCode/LeetCode] Jump Game I & II

    摘要:建立动规数组,表示从起点处到达该点的可能性。循环结束后,数组对所有点作为终点的可能性都进行了赋值。和的不同在于找到最少的步数。此时的一定是满足条件的最小的,所以一定是最优解。 Jump Game Problem Given an array of non-negative integers, you are initially positioned at the first index...

    rose 评论0 收藏0
  • [Leetcode] One Edit Distance 编辑距离为一

    摘要:比较长度法复杂度时间空间思路虽然我们可以用的解法,看是否为,但中会超时。这里我们可以利用只有一个不同的特点在时间内完成。 One Edit Distance Given two strings S and T, determine if they are both one edit distance apart. 比较长度法 复杂度 时间 O(N) 空间 O(1) 思路 虽然我们可以用...

    lewinlee 评论0 收藏0
  • Leetcode[161] One Edit Distance

    摘要:复杂度思路考虑如果两个字符串的长度,是肯定当两个字符串中有不同的字符出现的时候,说明之后的字符串一定要相等。的长度比较大的时候,说明的时候,才能保证距离为。 LeetCode[161] One Edit Distance Given two strings S and T, determine if they are both one edit distance apart. Stri...

    周国辉 评论0 收藏0
  • LeetCode[72] Edit Distance

    摘要:复杂度思路考虑用二维来表示变换的情况。如果两个字符串中的字符相等,那么如果两个字符串中的字符不相等,那么考虑不同的情况表示的是,从字符串到的位置转换到字符串到的位置,所需要的最少步数。 LeetCode[72] Edit Distance Given two words word1 and word2, find the minimum number of steps require...

    call_me_R 评论0 收藏0

发表评论

0条评论

snowell

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<