leetcode72:Edit Distance
阿新 • • 發佈:2018-12-11
思路:設dp[i][j]表示word1中0-i個字元轉換成word2中0-j個字元需要的最少次數,先對0行和0列所有元素進行初始化,然後從1行1列開始往後遞推,最終將dp陣列填充滿,dp[row][col]即為最終結果。
狀態轉移方程為:
if(word1[i]==word2[j]):
dp[i][j]=dp[i-1][j-1];
else:
dp[i][j]=Math.min(dp[i-1][j-1]+1, Math.min(dp[i][j-1]+1, dp[i-1][j]+1));
以“ros”和“horse”為例:
null | h | o | r | s | e |
|
null | 0 | 1 | 2 | 3 | 4 | 5 |
r | 1 | 1 | 2 | 2 | 3 | 4 |
o | 2 | 2 | 1 | 2 | 3 | 4 |
s | 3 | 2 | 2 | 2 | 2 | 3 |
程式碼:
public class EditDistance { public static void main(String[] args) { System.out.println(minDistance("ros","horse")); } public static 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 <= len2; i++) { dp[0][i]=i; } for (int i = 0; i <= len1; i++) { dp[i][0]=i; } for (int i = 1; i <= len1; i++) { for (int j = 1; j <= len2; j++) { if(word1.charAt(i-1)==word2.charAt(j-1)) dp[i][j]=dp[i-1][j-1]; else dp[i][j]=Math.min(dp[i-1][j-1]+1, Math.min(dp[i][j-1]+1, dp[i-1][j]+1)); } } // for (int i = 0; i < dp.length; i++) { // for (int j = 0; j < dp[0].length; j++) { // System.out.print(dp[i][j]+" "); // } // System.out.println(); // } return dp[len1][len2]; } }
輸出: