题目:找两个字符串的最长公共子串的最大长度
分析:从较短的那个子串的长度串依次判断是不是长串的子串,即从将可能的最长公共子串开始比较,那么只要匹配到,一定是最长的子串。
int max_common_str(const string& s1, const string& s2)
{
string longstr;
string shortstr;
if (s1.size() > s2.size())
{
longstr = s1;
shortstr = s2;
}
else
{
longstr = s2;
shortstr = s1;
}
//将短的字符串从长度为len,len-1...
string sub;
int lsub = 0;
int max = 0;
for (int len = shortstr.size(); len > 0; len--)
{
for (int i = 0; i <= shortstr.size() - len; i++)
{
sub = shortstr.substr(i, len);
if (strstr(longstr.c_str(), sub.c_str()))
{
lsub = sub.size();
}
}
//其实不需要这的
/*if (lsub > max)
{
max = lsub;
}*/
}
return max;
}