[LeetCode] 72. Edit Distance Java
题目:
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
题意及分析:从word1转化为word2需要的最小编辑步骤,步骤:删除一个字符、添加一个字符、替换一个字符。双序列动态规划问题,dp[i][j]表示第一个序列i ...和 第二个序列j ...;
1. 状态: dp[i][j]表示第一个字符串前i个字符到第二个字符串前j个字符需要的编辑距离;
2. 递推关系:
(1)如果 s1[i] == s2[j]
dp[i][j] =dp[i-1][j-1] //表示不需要任何编辑,直接可到达
(2)如果 s1[i] != s2[j],肯定需要进行一次变换
dp[i][j] = min(dp[i-1][j-1] ,dp[i-1][j],dp[i][j-1]) + 1 //分别代表替换,删除、增加
3. 初始化:
dp[i][0] = i; i = 1...m;
dp[0][j] = j; j = 1...n;
代码:
1 class Solution { 2 public int minDistance(String word1, String word2) { 3 int[][] dp = new int[word1.length()+1][word2.length()+1]; 4 5 for(int i=0;i<=word1.length();i++){ 6 dp[i][0] = i; 7 } 8 for(int i=0;i<=word2.length();i++){ 9 dp[0][i] = i; 10 } 11 12 for(int i=1;i<=word1.length();i++){ 13 for(int j=1;j<=word2.length();j++){ 14 if(word1.charAt(i-1)==word2.charAt(j-1)){ 15 dp[i][j] = dp[i-1][j-1]; 16 }else{ 17 dp[i][j] = Math.min(dp[i-1][j],Math.min(dp[i][j-1],dp[i-1][j-1]))+1; 18 } 19 } 20 } 21 return dp[word1.length()][word2.length()]; 22 } 23 }