求两个字符串的编辑距离。核心思想依然是动态规划,但是递归的时间复杂度太大,尽量用数组解决这种问题。
public int minDistance(String word1, String word2) {
int len1=word1.length()+1;
int len2=word2.length()+1;
int[][] s=new int[len1][len2];
for(int i=0;i<len1;i++){
s[i][0]=i;
}
for(int j=0;j<len2;j++){
s[0][j]=j;
}
for(int i=1;i<len1;i++){
for(int j=1;j<len2;j++){
if(word1.charAt(i-1)==word2.charAt(j-1)){
s[i][j]=s[i-1][j-1];
}
else{
s[i][j]=s[i-1][j-1]+1;
}
s[i][j]=min(s[i][j], s[i-1][j]+1,s[i][j-1]+1);
}
}
return s[len1-1][len2-1];
}
public int min(int a, int b, int c) {
if (a < b) {
if (b < c) {
return a;
} else {
if (a < c) {
return a;
} else {
return c;
}
}
} else {
if (a < c) {
return b;
} else {
if (b < c) {
return b;
} else {
return c;
}
}
}
}