典型的DP
1. Array怎么建?
这种有连续感的最值问题就可以直接建array表示到目前为止的最小值,此题中index表示length
涉及两个String,二维
2. changing condition?3种change
3. initial addition?
改进: -> 空间O(m) 用两个 int[m] 存cur,pre行 (同fibonacci number的改进思想)
-> lazy DP can be eager: http://www.csse.monash.edu.au/~lloyd/tildeStrings/Alignment/92.IPL.html
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
public class Solution {
public int minDistance(String word1, String word2) {
int len1 = word1.length();
int len2 = word2.length();
int[][] res = new int[len1+1][len2+1];
for (int i = 0; i <= len1; i++) {
res[i][0] = i;
}
for(int j = 0; j <= len2; j++) {
res[0][j] = j;
}
for (int m = 1; m <= len1; m++) {
for (int n = 1; n <= len2; n++) {
if (word1.charAt(m-1) == word2.charAt(n-1)){
res[m][n] = res[m-1][n-1];
} else {
res[m][n] = 1 + getMin(res[m-1][n-1], res[m-1][n], res[m][n-1]);
}
}
}
return res[len1][len2];
}
public int getMin(int a, int b, int c) {
return Math.min(a, Math.min(b, c));
}
}