Edit Distance

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

思路:

  动态规划

我的代码:

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

学习之处:

  • 最近做动态规划的题目也越来越有心得体会了,也能想的出来动态规划的方程是什么了,见多识广也就是这个意思吧,动态方程的想法也就是逆向思维的代表作
  • 动态规划的方程初始化比较烦人,往往是多初始化一行或者一列,这一行一列代表的是其中一个对象为空的情况,当一个对象为空的时候,想起动态规划的方程就好想多了。
  • 动态规划的问题,仔细的想明白了就可以了,真正写起代码来其实很少的,代码是很好写的,主要在思维。
  • 孰能生巧,改掉不好的习惯,抓住机会。

posted on 2015-05-10 11:24  zhouzhou0615  阅读(215)  评论(0编辑  收藏  举报

导航