首页 技术 正文
技术 2022年11月19日
0 收藏 533 点赞 4,351 浏览 1305 个字

LintCode 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:

  • Insert a character
  • Delete a character
  • Replace a character

Example

  • Given word1 = “mart” and word2 = “karma”, return 3

For this problem, the dynamic programming is used.

Firstly, define the state MD(i,j) stand for the int number of minimum distance of changing i-char length word to j-char length word. MD(i, j) is the result of editing word1 which has i number of chars to word2 which has j number of word.

Second, we want to see the relationship between MD(i,j) with MD(i-1, j-1) ,  MD(i-1, j) and MD(i, j-1).

Thirdly, initilize all the base case as MD(i, 0) = i, namely that delete all i-char-long word to zero and MD(0, i) = i, namely insert zero length word to i-char-long word.

Fourth, solution is to calculate MD(word1.length(), word2.length())

 public class Solution {
/**
* @param word1 & word2: Two string.
* @return: The minimum number of steps.
*/
public int minDistance(String word1, String word2) {
int n = word1.length();
int m = word2.length();
int[][] MD = new int[n+][m+]; for (int i = ; i < n+; i++) {
MD[i][] = i;
} for (int i = ; i < m+; i++) {
MD[][i] = i;
} for (int i = ; i < n+; i++) {
for (int j = ; j < m+; j++) {
//word1's ith element is equals to word2's jth element
if(word1.charAt(i-) == word2.charAt(j-)) {
MD[i][j] = MD[i-][j-];
}
else {
MD[i][j] = Math.min(MD[i-][j-] + ,Math.min(MD[i][j-] + , MD[i-][j] + ));
}
}
}
return MD[n][m];
}
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,994
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,507
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,350
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,135
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,768
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,845