Problem
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:
Insert a character
Delete a characterReplace a characterExample
Given word1 = "mart
" and word2 = "karma
", return 3
.
Note
构造dp[i][j]
数组,i
是word1
的index+1
,j
是word2
的index+1
,dp[i][j]
是将i位的word1转换成j位的word2需要的步数。初始化dp[i][0]
和dp[0][i]
为dp[0][0]
到它们各自的距离i
,然后两次循环i
和j
即可。
i-->j-1
之后,再插入一位才完成i-->j
;deletion是完成i-->j
之后,发现i多了一位,所以i-1-->j
才是所求,需要再删除一位才完成i-->j
;而replacement则是换掉word1的最后一位,即之前的i-1-->j-1
已经完成,如果word1的第i-1位和word2的第j-1位相等,则不需要替换操作,否则要替换一次完成i-->j
。 Solution
public class Solution { public int minDistance(String word1, String word2) { int m = word1.length(), n = word2.length(); int[][] dp = new int[m+1][n+1]; for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0) dp[i][j] = j; else if (j == 0) dp[i][j] = i; else { int insert = dp[i][j-1] + 1; int delete = dp[i-1][j] + 1; int replace = dp[i-1][j-1] + (word1.charAt(i-1) == word2.charAt(j-1) ? 0 : 1); dp[i][j] = Math.min(insert, Math.min(delete, replace)); } } } return dp[m][n]; }}