|
| 1 | +packageAlgorithms.dp; |
| 2 | + |
| 3 | +publicclassMinDistance { |
| 4 | +publicintminDistance(Stringword1,Stringword2) { |
| 5 | +// THE DP FORMULA |
| 6 | +// D[i][j]: The min operations to change from s1 to s2. |
| 7 | +// s1: i characters in word1, s2: j characters in word2. |
| 8 | +// |
| 9 | +// D[i][j] = |
| 10 | + |
| 11 | +if (word1 ==null ||word2 ==null) { |
| 12 | +return -1; |
| 13 | + } |
| 14 | + |
| 15 | +intlen1 =word1.length(); |
| 16 | +intlen2 =word2.length(); |
| 17 | + |
| 18 | +// create a DP array. |
| 19 | +// 注意:一定要多分配1个。 |
| 20 | +// 取0表示从string中一个都不取 |
| 21 | +int[][]D =newint[len1 +1][len2 +1]; |
| 22 | + |
| 23 | +for (inti =0;i <=len1;i++) { |
| 24 | +for (intj =0;j <=len2;j++) { |
| 25 | +if (i ==0 &&j ==0) { |
| 26 | +D[i][j] =0; |
| 27 | + }elseif (i ==0) { |
| 28 | +// Need to add a new element to do it. |
| 29 | +D[i][j] =D[i][j -1] +1; |
| 30 | + }elseif (j ==0) { |
| 31 | +// Need to delete a element to get the string 2. |
| 32 | +D[i][j] =D[i -1][j] +1; |
| 33 | + }else { |
| 34 | +// we can come from 3 options: |
| 35 | +// 1. D[i][j - 1] |
| 36 | +// 2. D[i - 1][j] |
| 37 | +// 3. D[i - 1][j - 1] |
| 38 | +D[i][j] =Math.min(D[i][j -1] +1,D[i -1][j] +1); |
| 39 | + |
| 40 | +// 注意这里的Index是 i - 1 跟 j - 1. |
| 41 | +// 因为i的意思是从string1取出i个字符,所以最后一个字符的索引是i - 1 |
| 42 | +if (word1.charAt(i -1) ==word2.charAt(j -1)) { |
| 43 | +// 最后一个字符相等,不需要变化 |
| 44 | +D[i][j] =Math.min(D[i][j],D[i -1][j -1]); |
| 45 | + }else { |
| 46 | +// 最后一个字符不等,需要replace. |
| 47 | +D[i][j] =Math.min(D[i][j],D[i -1][j -1] +1); |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | +returnD[len1][len2]; |
| 54 | + } |
| 55 | +} |