难度:2
求编辑距离。。。
opt[i][j]表示word1的前i个字符与word2的前j个字符的editdistance
word1[i-1] == word2[j-1] opt[i][j]=opt[i-1][j-1]
word1[i-1] != word2[j-1] opt[i][j]=min(opt[i-1][j]+1,opt[i][j-1]+1,opt[i-1][j-1]+1)
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
class Solution
{
public:
int minDistance(string word1, string word2)
{
int m=word1.size();
int n=word2.size();
//opt[i][j]表示word1的前i个字符与word2的前j个字符的editdistance
//word1[i-1] == word2[j-1] opt[i][j]=opt[i-1][j-1]
//word1[i-1] != word2[j-1] opt[i][j]=min(opt[i-1][j]+1,opt[i][j-1]+1,opt[i-1][j-1]+1)
int **opt=new int*[2];
opt[0] = new int[n+1];
opt[1] = new int[n+1];
for(int i=0;i<=n;i++)
{
opt[0][i]=i;
}
for(int i=1,now=1;i<=m;i++,now^=1)
{
opt[now][0]=i;
for(int j=1;j<=n;j++)
{
if(word1[i-1] == word2[j-1]) opt[now][j]=opt[now^1][j-1];
else
{
opt[now][j]=opt[now^1][j]+1;
opt[now][j]=min(opt[now][j],opt[now][j-1]+1);
opt[now][j]=min(opt[now][j],opt[now^1][j-1]+1);
}
}
}
int ans=opt[m&1?1:0][n];
delete [] opt[0];
delete [] opt[1];
delete [] opt;
return ans;
}
};