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
設狀態為f[i][j],表示A[0,i] 和B[0,j] 之間的最小編輯距離。設A[0,i] 的形式是str1c,B[0,j] 的形式是str2d,
1. 如果c==d,則f[i][j]=f[i-1][j-1];
2. 如果c!=d,
(a) 如果將c 替換成d,則f[i][j]=f[i-1][j-1]+1;
(b) 如果在c 後面添加一個d,則f[i][j]=f[i][j-1]+1;
(c) 如果將c 刪除,則f[i][j]=f[i-1][j]+1;
源碼:Java版本
算法分析:二維動態規劃。時間復雜度O(m*n),空間復雜度O(m*n)
public class Solution { public int minDistance(String word1, String word2) { int m=word1.length(); int n=word2.length(); int[][] f=new int[m+1][n+1]; for(int i=0;i