leetcode 72. Edit Distance
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
首先考虑如何简化问题,例如“ABC”和“DBA”如何算编辑距离。
先把问题简化为只有一个字符'A'和‘D'.那么只需要把A换为D就可以了。
然后看“A”和“DB”,需要把A更新B,然后在插入B,两步。 。。。
定义表达式D(i,j)。它表示从第1个字单词的第0位至第i位形成的子串和第2个单词的第0位至第j位形成的子串的编辑距离。
显然,
D(i,0) = i //删除i次变为空串
D(0,j) = j
状态转移方程是:
D(i,j)=min ( D(i-1, j) + 1 //word1 (删除、新增、替换) 第i个字符
D(i, j-1) + 1 ) //word2 (删除、新增、替换) 第j个字符
D(i-1, j-1) + 1 //word1第i个字符和word2第 j个字符相等
D(i-1,j-1) //word1第i个字符和word2第 j个字符相等
public class Solution { public int minDistance(String word1, String word2) { int len1=word1.length(); int len2=word2.length(); int [][] path=new int[len1+1][len2+1]; for(int i=0;i<=len1;i++){ path[i][0]=i; } for(int j=0;j<=len2;j++){ path[0][j]=j; } for(int i=1;i<=len1;i++){ for(int j=1;j<=len2;j++){ int temp; if( word1.charAt(i-1)==word2.charAt(j-1))//i,j是path的下标,字符下表要-1 temp=path[i-1][j-1]; else temp=1+path[i-1][j-1]; int temp2=Integer.min(path[i-1][j]+1,path[i][j-1]+1); path[i][j]=Integer.min(temp2,temp); } } return path[len1][len2]; } }