标签:
这事实上是一道二维动态规划的题目。模型上确实不easy看出来。以下我们来说说递推式。
上面列举的情况包括了全部可能性。有朋友可能会说为什么没有删除操作,事实上这里加入一个插入操作永远能得到与一个删除操作同样的效果。所以删除不会使最少操作数变得更好,因此假设我们是正向考虑。则不须要删除操作。取上面几种情况最小的操作数,即为另外一种情况的结果。即res[i][j] = min(res[i-1][j], res[i][j-1], res[i-1][j-1])+1。
代码例如以下:
public int minDistance(String word1, String word2) {
if(word1.length()==0)
return word2.length();
if(word2.length()==0)
return word1.length();
String minWord = word1.length()>word2.length()?word2:word1;
String maxWord = word1.length()>word2.length()?word1:word2;
int[] res = new int[minWord.length()+1];
for(int i=0;i<=minWord.length();i++)
{
res[i] = i;
}
for(int i=0;i<maxWord.length();i++)
{
int[] newRes = new int[minWord.length()+1];
newRes[0] = i+1;
for(int j=0;j<minWord.length();j++)
{
if(minWord.charAt(j)==maxWord.charAt(i))
{
newRes[j+1]=res[j];
}
else
{
newRes[j+1] = Math.min(res[j],Math.min(res[j+1],newRes[j]))+1;
}
}
res = newRes;
}
return res[minWord.length()];
}
上面代码用了minWord,
maxWord是为了使得空间是min(m,n)。细节做得比較细,面试的时候可能不用刻意这么做。提一下就好。版权声明:本文博主原创文章,博客,未经同意不得转载。
标签:
原文地址:http://www.cnblogs.com/lcchuguo/p/4825527.html