题目
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
动态规划经典题目,找到递推关系,初始化,然后递推。
这里的dp[i][j]表示word1.substring(0, i+1)和word2.substring(0, j+1)的最小编辑距离。
代码
public class EditDistance { public int minDistance(String word1, String word2) { char[] word1CharArray = word1.toCharArray(); char[] word2CharArray = word2.toCharArray(); int M = word1CharArray.length; int N = word2CharArray.length; if (M == 0 || N == 0) { return M + N; } int[][] dp = new int[M][N]; // init dp[0][0] = word1CharArray[0] == word2CharArray[0] ? 0 : 1; for (int i = 1; i < M; ++i) { dp[i][0] = word1CharArray[i] == word2CharArray[0] ? i : dp[i - 1][0] + 1; } for (int j = 1; j < N; ++j) { dp[0][j] = word1CharArray[0] == word2CharArray[j] ? j : dp[0][j - 1] + 1; } // dp for (int i = 1; i < M; ++i) { for (int j = 1; j < N; ++j) { if (word1CharArray[i] == word2CharArray[j]) { dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + 1; dp[i][j] = Math.min(dp[i][j], dp[i - 1][j - 1]); } else { dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]); dp[i][j] = Math.min(dp[i][j], dp[i - 1][j - 1]) + 1; } } } return dp[M - 1][N - 1]; } }
LeetCode | EditDistance,布布扣,bubuko.com
原文:http://blog.csdn.net/perfect8886/article/details/21565173