最小編輯距離?
給出兩個單詞word1和word2,計算出將word1 轉換為word2的最少操作次數。
你總共三種操作方法:
- 插入一個字符
- 刪除一個字符
- 替換一個字符
樣例
給出 work1="mart" 和 work2="karma"
返回 3
解題
動態規劃解題
定義矩陣dp[][]
dp[i][j] 表示word1前i個字符 [0,1,2,...,i-1] 和 word2前j個字符?[0,1,2,...,j-1]的編輯距離
?
ch1 = word1.charAt(i)
ch2 = word2.charAt(j)
當 ch1== ch2:word1[0--(i-1)] 與word2[0--(j-1)] 的編輯距離dp[i][j] = dp[i-1][j-1] 不需要修改
當ch1!=ch2: 有三種修改方式
- ch1替換word2中的ch2,此時的編輯距離受上一位的編輯距離影響, 編輯距離是:dp[i-1][j-1] + 1
- ? ? ? ? ? ? ? ? ? ch2插入到word1中ch1的前面,word1中的ch2還沒有比較,編輯距離是:dp[i-1][j] + 1
- ? ? ? ? ? ? ? ? ? 刪除ch2 編輯距離:dp[i][j-1] + 1
選取上面的最小值更新dp[i][j]的值
Java程序定義的dp矩陣長度是len1 + 1 * len2 + 1 的和上面有一點區別?
import java.util.Scanner; // write your code here public class Main{public static void main(String[] args){Scanner in = new Scanner(System.in);Main m = new Main();while(in.hasNext()){String[] str = in.nextLine().split(" ");String word1 = str[0];String word2 = str[1];int min = m.minDistance(word1,word2);System.out.println(min);}}public int minDistance(String word1,String word2){int len1 = word1.length();int len2 = word2.length();int[][] dp = new int[len1+1][len2+1];for(int i =0;i<=len1;i++){dp[i][0] = i;}for(int j =0;j<= len2;j++){dp[0][j] = j;}for(int i =0;i< len1;i++){char ch1 = word1.charAt(i);for(int j =0;j< len2;j++){char ch2 = word2.charAt(j);if(ch1 == ch2){dp[i+1][j+1] = dp[i][j];}else{int replace = dp[i][j] +1;// ch1 代替 ch2int insert = dp[i][j+1] + 1;// ch2 插入到 ch1 前面的位置int delete = dp[i+1][j] + 1;// 刪除ch2int min =replace>insert?insert:replace;min = min>delete?delete:min;dp[i+1][j+1] = min;}}}return dp[len1][len2];} }
?注:搜狐2016實習筆試題目