• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

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

典型DP,很难想,知道方法后就很容易实现了

这道题叫Edit Distance,因为Edit Distance定义就是:Given two string S1, S2, the minimum number of operations to convert one into another.

https://www.youtube.com/watch?v=CB425OsE4Fo&list=PL0174E49C0E0DD5C8&index=35这个视频讲的很好,关注20:00, 31:54, 34:32等处

res[i][j]表示Edit Distance between X数组的前i个元素以及Y数组的前j个元素,或者the minimum # of operations to convert X前i个元素 into Y的前j个元素

因为对于Xi 和 Yj,操作无非是 insert, delete, replace三种,所以递归式就是三项:根据上面这个图很清楚:res[i][j] = min{res[i-1][j]+1, res[i][j-1]+1, Xi == Yj ? res[i-1][j-1] : res[i-1][j-1] + 1}

 1 public class Solution {
 2     public int minDistance(String word1, String word2) {
 3         if (word1==null && word2!=null) return word2.length();
 4         if (word1!=null && word2==null) return word1.length();
 5         if (word1==null && word2==null) return 0;
 6         int[][] res = new int[word1.length()+1][word2.length()+1];
 7         for (int i=1; i<=word1.length(); i++) {
 8             res[i][0] = i;
 9         }
10         for (int j=1; j<=word2.length(); j++) {
11             res[0][j] = j;
12         }
13         for (int m=1; m<=word1.length(); m++) {
14             for (int n=1; n<=word2.length(); n++) {
15                 res[m][n] = Math.min(Math.min(res[m-1][n]+1, res[m][n-1]+1), word1.charAt(m-1)==word2.charAt(n-1)? res[m-1][n-1] : res[m-1][n-1]+1);
16             }
17         }
18         return res[word1.length()][word2.length()];
19     }
20 }

 

posted @ 2014-10-08 06:10  neverlandly  阅读(742)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3