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 characterb) Delete a character
c) Replace a character
题目要求找出转换word1到word2的最小步数,插入,删除,替换一个字符都算作一步。
这题乍一看没思路,感觉情况相当多,无从分析起,后面看了下题目的提示,需要用到动态规划,自己花了个矩阵,豁然开朗。
我们可以新建一个m*n大小的整型数组dis,其中dis[i][j]表示word1前i个字母到word2前j个字母所需要的最小步数,m和n分别表示word1,word2的长度.
下面分三种情况进行讨论:
1)dis[i][j] = dis[i-1][j] + 1; 在word1中插入了一个字符(或者相当于word2中相同位置删除一个字符),步数+1
2)dis[i][j] = dis[i][j-1] + 1; 在word2中插入了一个字符(或者相当于word1中相同位置删除一个字符),步数+1
3)dis[i][j] = dis[i-1][j-1] + val[i-1][j-1]; 在word1中第i个位置(或者word2中第j个位置)替换了一个字符,如果word1[i] == word2[j],那么val = 0,否则val =1;
显然 dis[i][j] 取三种情况的最小值。
java实现如下:
public class Solution {
public int minDistance(String word1, String word2) {
int[][] dis = new int[word1.length()+1][word2.length()+1];
for(int i = 0 ; i < word1.length()+1 ; i++){
for(int j = 0 ; j < word2.length()+1 ; j ++){
if( i == 0)
dis[i][j] = j;
else if( j == 0)
dis[i][j] = i;
else{
int min = dis[i][j-1] + 1;
int val = word1.charAt(i-1) == word2.charAt(j-1) ? 0 : 1;
min = min < dis[i-1][j] +1 ? min : dis[i-1][j] +1;
dis[i][j] = min < dis[i-1][j-1] +val ? min : dis[i-1][j-1] +val;
}
}
}
return dis[word1.length()][word2.length()];
}
}