我開始還以爲是最長公共子串,結果在字符串中間也可以刪除字符,那就變成了最長公共子序列了。上一篇有的。
class Solution {
public:
int xwa(string s1, string s2)
{
int x=(int)s1.length();
int y=(int)s2.length();
if(0==x || 0==y)
return 0;
vector<vector<int>>a(x,vector<int>(y,-1));
if(s1[0]==s2[0])
a[0][0]=1;
else
a[0][0]=0;
for(int i=1;i<x;++i)
{
if(s1[i]==s2[0]||(s1[i]!=s2[0] && 1 == a[i-1][0]))
a[i][0]=1;
else
a[i][0]=0;
}
for(int j=1;j<y;++j)
{
if(s1[0] == s2[j]||(s1[0]!=s2[j]&& 1==a[0][j-1]))
a[0][j]=1;
else
a[0][j]=0;
}
for(int i=1;i<x;++i)
{
for(int j=1;j<y;++j)
{
if(s1[i]==s2[j])
a[i][j]=max(max(a[i-1][j], a[i][j-1]),a[i-1][j-1]+1);
else
a[i][j]=max(a[i-1][j], a[i][j-1]);
}
}
return a[x-1][y-1];
}
int minDistance(string word1, string word2) {
int x=xwa(word1,word2);
return word1.length()+word2.length()-x-x;
}
};