题目:
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
题意:
给定两个单词word1 and word2,找出从word1变为word2 所需要的最少的步数.(每次操作被看为一步.)
对于每个单词你能够有如下的三种操作:
a) 插入一个字符
b) 删去一个字符
c) 替换一个字符
算法分析:
动态规划
初始情况: dp[i][0] = i (0 <= i <= word1 length), dp[0][j] = j (0 <= j <= word2 length).
初始化的时候我们是在第0行,也就是另一个字符串一个字符都不取,即空字符串。 res[i]表示如何将当前字符串(前i个元素)变成一个空字符串, 所以我们可以进行i次删除(或者插入)操作,就可以使得当前字符串变成空字符串(或者空字符串变成当前字符串)
* dp[i][j]表示word1前i个字母变成word2前j个字母的步数(edit distance)。
*
* 如果word1的第i个字母等于word2的第j个字母, 则dp[i][j] = dp[i-1][j-1]。如果不等, 则有三种情况:
*
* 1) 把word1的前i-1个字母变成word2的前j-1个字母, 再把word1的第i个字母换成word2的第j个字母, 即dp[i-1][j-1] + 1
*
* 2) 把word1的前i个字母变成word2的前j-1个字母, 再加上word2的第j个字母, 即dp[i][j-1] + 1
*
* 3) 删掉word1的第i个字母, 把word1的前i-1个字母变成word2的前j个字母, 即1 + dp[i-1][j]
AC代码:
public class Solution
{
public static int minDistance(String word1, String word2)
{
int len1 = word1.length();
int len2 = word2.length();
// len1+1, len2+1, because finally return dp[len1][len2]
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;
//iterate though, and check last char
for (int i = 1; i <= len1; i++)
{
char c1 = word1.charAt(i-1);
for (int j = 1; j <= len2; j++)
{
char c2 = word2.charAt(j-1);
//if last two chars equal
if (c1 == c2)
{
//update dp value for +1 length
dp[i][j] = dp[i-1][j-1];
}
else
{
//把word1的前i-1个字母变成word2的前j-1个字母, 再把word1的第i个字母换成word2的第j个字母, 即dp[i-1][j-1] + 1
int replace = dp[i-1][j-1] + 1;
int delete = 1 + dp[i-1][j] ;//删掉word1的第i个字母, 把word1的前i-1个字母变成word2的前j个字母, 即1 + dp[i-1][j]
int insert= dp[i][j-1] + 1;//把word1的前i个字母变成word2的前j-1个字母, 再加上word2的第j个字母, 即dp[i][j-1] + 1
int min = Math.min(replace, insert);
min = Math.min(min,delete);
dp[i][j] = min;
}
}
}
return dp[len1][len2];
}
}
参考:
http://www.cnblogs.com/springfor/p/3896167.html?utm_source=tuicool
http://blog.csdn.net/linhuanmars/article/details/24213795
http://chaoren.is-programmer.com/posts/44402.html