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
将word1变化为word2所需的最少步骤,每个步骤可以执行:删除一个任意字符,增加一个任意字符,改变一个字符为其他任意字符
思路:使用dp[i][j]表示word1的(0,i)子串变化为word2的(0,j)子串所需要的步骤数,根据上面的三个变化规则
dp[i][j] = min{dp[i-1][j] + 1,dp[i][j-1] + 1, dp[i-1[j-1] + 1}
如果wrod1[i] == word2[j]
那么dp[i][j] = min{dp[i][j], dp[i-1][j-1]}
class Solution {
public int minDistance(String word1, String word2) {
char[] cha = word1.toCharArray(), chb = word2.toCharArray();
int lena = cha.length, lenb = chb.length;
if(lena == 0 || lenb == 0)
return lena + lenb;
int[][] record = new int[lena + 1][lenb + 1];
for(int[] it : record)
Arrays.fill(it, 9999);
for(int i = 0; i < lena + 1; i++){
for(int j = 0; j < lenb + 1; j++){
if(i == 0 || j == 0){
record[i][j] = i + j;
continue;
}
record[i][j] = Math.min(record[i - 1][j - 1] + 1, record[i][j]);
record[i][j] = Math.min(record[i - 1][j] + 1, record[i][j]);
record[i][j] = Math.min(record[i][j - 1] + 1, record[i][j]);
if(cha[i - 1] == chb[j - 1])
record[i][j] = Math.min(record[i - 1][j - 1], record[i][j]);
//System.out.print(record[i][j] + " ");
}
//System.out.println();
}
return record[lena][lenb];
}
}