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
这道题主要是很难想出来,编程倒不是很难。
是一个很经典的动态规划题 ,非常超出我的水平。
我主要是看了一下这些博客,基本搞懂了流程:
http://blog.youkuaiyun.com/luo123n/article/details/9999481 讲解了原理
http://www.cnblogs.com/biyeymyhjob/archive/2012/09/28/2707343.html 比较形象,可以参考这里的图看其他的文章。
弄懂了原理以后写实现代码是很easy的,主要是算一个二维数组就行了。代码如下:
public int minDistance(String word1, String word2) {
int len1 = word1.length();
int len2 = word2.length();
int temp1,temp2,temp3;
int[][] distance = new int[len1+1][len2+1];
for(int i = 0; i <= len2; i++){
distance[0][i] = i;
}
for(int i = 1; i <= len1; i++){
distance[i][0] = i;
}
for(int i = 1; i <=len1; i++){
for(int j = 1; j <= len2; j++){
temp1 = distance[i-1][j] + 1;
temp2 = distance[i][j-1] + 1;
if(word1.charAt(i-1) == word2.charAt(j-1)){
temp3 = distance[i-1][j-1];
}else{
temp3 = distance[i-1][j-1] + 1;
}
distance[i][j] = minInThree(temp1, temp2, temp3);
}
}
return distance[len1][len2];
}
private int minInThree(int num1, int num2, int num3){
if(num1<= num2){
if(num1 <= num3){
return num1;
}else{
return num3;
}
}else{
if(num2 <= num3){
return num2;
}else{
return num3;
}
}
}