设为首页 加入收藏

TOP

[LeetCode]Edit Distance
2015-07-20 17:16:41 来源: 作者: 【 】 浏览:2
Tags:LeetCode 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

Example
Given work1=”mart” and work2=”karma”

return 3

解题思路

参考了网上解法,http://www.cnblogs.com/lihaozy/archive/2012/12/31/2840152.html
对于作者给出解答程序没来得及仔细看,但是二维数组中的下标中有0的元素数据初始化我按照自己的想法来的。

程序

public class Solution {
    /**
     * @param word1 & word2: Two string.
     * @return: The minimum number of steps.
     */
    public int minDistance(String word1, String word2) {
        if (word1.length() == 0 || word2.length() == 0)
            return Math.max(word1.length(), word2.length());

        int[][] dp = new int[word1.length()][word2.length()];

        for (int i = 0; i < word1.length(); i++) {
            for (int j = 0; j < word2.length(); j++) {
                if (i == 0 && j == 0) {
                    if (word1.charAt(i) == word2.charAt(j))
                        dp[i][j] = 0;
                    else
                        dp[i][j] = 1;
                } else if (i == 0 || j == 0) {
                    if (word1.charAt(i) == word2.charAt(j))
                        dp[i][j] = Math.max(i, j);
                    else if (i == 0)
                        dp[i][j] = dp[i][j - 1] + 1;
                    else if (j == 0)
                        dp[i][j] = dp[i - 1][j] + 1;
                } else {
                    if (i > 0 && j > 0) {
                        dp[i][j] = dp[i - 1][j - 1]; // 字符相同
                        if (word1.charAt(i) != word2.charAt(j))
                            dp[i][j] = dp[i - 1][j - 1] + 1;// 字符不相同
                    }
                    dp[i][j] = Math.min(dp[i][j], dp[i - 1][j] + 1); // 和word1减一个字符比
                    dp[i][j] = Math.min(dp[i][j], dp[i][j - 1] + 1); // 和word2减一个字符比
                }
            }
        }
        return dp[word1.length() - 1][word2.length() - 1];
    }
}
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇hdu 1372 Knight Moves BFS解法 下一篇[LeetCode]Distinct Subsequences

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·怎样用 Python 写一 (2025-12-27 02:49:19)
·如何学习python数据 (2025-12-27 02:49:16)
·想要自学数据分析, (2025-12-27 02:49:14)
·Java 集合框架 - 菜 (2025-12-27 02:19:36)
·Java集合框架最全详 (2025-12-27 02:19:33)