题意:将一个字符串转为另外一个字符串需要的步数,可以插入、删除、替换一个字符,求需要的最少的操作步数。
思路:动规解决。Distance[i][j]记录操作步数。
考虑str1c和str2d,若是c == d,则Distance[i][j] = Distance[i-1][j] +1;
若是在c后面添加一个d,则是Distance[i][j] = Distance[i][j-1] +1;
若是将c删除,则是Distance[i][j] = Distance[i-1][j] +1;
代码:
package com.editDistance;
public class editDistance {
public int calDistance(String word1 , String word2){
int m = word1.length();
int n = word2.length();
int[][] Distance = new int[m+1][n+1];
for (int i = 0; i < m; i++) {
Distance[i][0] = i;
}
for (int i = 0; i < n; i++) {
Distance[0][i] = i;
}
for(int i = 1 ; i <= m ; i++){
for(int j = 1 ; j<= n ;j++){
if(word1.charAt(i-1) == word2.charAt(j-1)){
Distance[i][j] = Distance[i-1][j-1];
}
else{
int dis = Math.min(Distance[i-1][j], Distance[i][j-1]);
Distance[i][j] = 1+Math.min(dis, Distance[i-1][j-1]);
}
}
}
return Distance[m][n];
}
public static void main(String[] args) {
//若word1需要修改的字符数大于word2的长度,则操作的步数直接是word2的长度(先一步步删除word2,再进行替换)
String word1 = "nex12345vsfvfvev";
String word2 = "nex12";
System.out.println(new editDistance().calDistance(word1, word2));
}
}