File tree 1 file changed +32
-0
lines changed
1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change
1
+ //建立数组dp[][]来存储 以word1[i]为结尾的字符串 转换成 以word2[j]为结尾的字符串 所需的最小操作数
2
+ //当新遍历一对来自word1,word2的字符
3
+ //若 word1[i] == word2[j] 表示不需要操作,则dp[i][j]=dp[i-1][j-1]
4
+ //若 word1[i] != word2[j] 则可以有三种情况
5
+ // 1、替换 word1[i] 把 word1[i] 替换成 word2[j] 需要 dp[i-1][j-1]+1步
6
+ // 2、删除 word1[i] 把 word1[i] 删除成 word1[i-1] 需要 dp[i][j-1]+1步
7
+ // 3、删除 word2[j] 把 word2[j] 删除成 word2[j-1] 需要 dp[i-1][j]+1步(增加word1和删除word2一个效果)
8
+ // 取这三个中最小值
9
+ class Solution {
10
+ public int minDistance (String word1 , String word2 ) {
11
+ int len1 = word1 .length ();
12
+ int len2 = word2 .length ();
13
+ int [][] dp = new int [len1 +1 ][len2 +1 ];
14
+
15
+ for (int i = 1 ; i <= len1 ; i ++) {
16
+ dp [i ][0 ] = i ;
17
+ }
18
+ for (int i = 1 ; i <= len2 ;i ++) {
19
+ dp [0 ][i ] = i ;
20
+ }
21
+ for (int i = 1 ; i <= len1 ; i ++) {
22
+ for (int j = 1 ; j <= len2 ; j ++) {
23
+ if (word1 .charAt (i -1 ) == word2 .charAt (j -1 )) {
24
+ dp [i ][j ] = dp [i -1 ][j -1 ];
25
+ } else {
26
+ dp [i ][j ] = Math .min (dp [i -1 ][j -1 ] , Math .min (dp [i -1 ][j ],dp [i ][j -1 ])) + 1 ;
27
+ }
28
+ }
29
+ }
30
+ return dp [len1 ][len2 ];
31
+ }
32
+ }
You can’t perform that action at this time.
0 commit comments