算法思想來自:http://blog.csdn.net/shaohui/archive/2006/06/09/784577.aspx
/*
s1 = "abcdefg", s2 = "klmncdf"
abcdefg | abcdefg | abcdefg | abcdefg
klmncdf | klmncdf | klmncdf | klmncdf
s1慢慢滑過s2
*/
#include<iostream>
#include<string>
using namespace std;
// 返回最大公共子串長度
int bigsubstring(const string &str1, const string &str2)
{
int len1 = str1.length(), len2 = str2.length(), len = len1 + len2;
int cnt, idx; // 迭代量
int curmax, max; // curmax:當前公共子串最大長度,max:要返回的最大公共子串長度
int s1start, s2start; // 兩字符串開始遍歷的位置
max = 0;
for(cnt = 0; cnt < len; ++cnt)
{
s1start = 0;
s2start = 0;
if(cnt < len1)
s1start = len1 - cnt;
else
s2start = cnt - len1;
curmax = 0;
for(idx = 0; (s1start + idx < len1) && (s2start + idx < len2); ++idx)
{
if(str1[s1start + idx] == str2[s2start + idx])
curmax++;
else
{
max = (curmax > max) ? curmax : max;
curmax = 0;
}
}
max = (curmax > max) ? curmax : max;
} // 1st for
return max;
}
int main()
{
string s1, s2;
cin >> s1 >> s2;
cout << bigsubstring(s1, s2) << endl;
return 0;
}