参考:http://blog.youkuaiyun.com/yysdsyl/article/details/4249245
/*
与最长公共子串有关
题目描述:
要求两字符串有差异的字符个数。例如:
aaaaabaaaaa
aaaaacaabaa
这两个字符串,最大公共字串长度是5,但它们只有两个字符不同,函数输出值应为2。
如果是:
aaabbbcccddd
aaaeeeddd
函数的输出值应该是6。
比较形象地形容一下,把两个字符串排成上下两行,每个字符串都可以在任何位置插入空格以便上下对齐,每个列上至少有一个字符来自这两个字符串。当对齐程度最高的时候,没有对上的列的数即为函数输出值。
aaabbbcccddd
aaaeeeddd
最优对齐状态是:
aaabbbcccddd
aaaeee ddd
没有对上的列是6,函数输出值为6。
如果是:
abcde
acefg
最优对齐状态是:
abcde
a c efg
没有对上的列数是4,函数输出值为4。
核心:先求最长公共子串,再与两个字符串长度相减。
*/
#include <iostream>
#include <string>
using namespace std;
int LongestCommonStr(const string& str1,const string& str2)
{
const int str1Len=str1.length();
const int str2Len=str2.length();
int**p=new int*[str1Len+1];
for ( int i=0 ; i<=str1Len ; ++i ){
p[i]=new int[str2Len+1];
}
for ( int i=0 ; i<=str1Len ; ++i ){
memset(p[i],0,(str2Len+1)*4);
}
//求最长公共子串
for ( int i=1 ; i<=str1Len ; ++i ){
for ( int j=1 ; j<=str2Len ; ++j ){
if ( str1[i-1]==str2[j-1] ){
p[i][j]=p[i-1][j-1]+1;
} else {
p[i][j]= p[i-1][j]>p[i][j-1] ? p[i-1][j]:p[i][j-1];
}
}
}
return str1Len+str2Len-2*p[str1Len][str2Len];
}
int main()
{
string str1="ab";
string str2="a";
cout<<LongestCommonStr(str1,str2)<<endl;
return 0;
}