2、给定一个query和一个text,均由小写字母组成,要求在text中找出以同样的顺序连续出现在query中的最长连续字母序列的长度。例如,query为“acbac”,text为”acaccbabb”,那么text中的”cba”为最长的连续出现在query中的字母序列,因此,返回结果应该为其长度3.请注意程序效率。
方法一:
设短串的长度为n,长串的长度为m,现给出时间复杂度为O((m+n)*n)的算法
#include<string>
#include <iostream>
using namespace std;
int cmpute_maxlen(string &long_str,int start1,string &short_str,int start2)
{
int count=0,maxcount=0;
while(start1<long_str.size()&&start2<short_str.size())
{
if (long_str[start1++]==short_str[start2++])
{
count++;
}
else
{
maxcount=max(maxcount,count);
count=0;
}
}
return max(maxcount,count);
}
int _tmain(int argc, _TCHAR* argv[])
{
string a,b;
cin>>a;
cin>>b;
int count=0;
int maxcount=0;
string long_str=a.size()>b.size()?a:b;
string short_str=a.size()>b.size()?b:a;
int short_len=short_str.size();
for (int i=long_str.size()-1;i>-short_len;--i)
{
if (i>=0)
{
count=cmpute_maxlen(long_str,i,short_str,0);
maxcount=max(maxcount,count);
}
else
{
count=cmpute_maxlen(long_str,0,short_str,-i);
maxcount=max(maxcount,count);
}
}
cout<<maxcount<<endl;
system("pause");
return 0;
}
方法二:
时间复杂度为O(m*m*n)
int cmpute_maxlen_wujing(string a,string b)
{
int count=0, maxcount=0;
string long_str=a.size()>b.size()?a:b;
string short_str=a.size()>b.size()?b:a;
for (int i=0;i<short_str.size();++i)
{
int short_start=i;
count=0;
for (int j=0;j<long_str.size();++j)
{
if (long_str[j]==short_str[short_start])
{
++count;
++short_start;
if (short_start==short_str.size())
{
maxcount=max(maxcount,count);
break;
}
}
else
{
maxcount=max(maxcount,count);
j-=count;
count=0;
short_start=i;//注意回i
}
}
}
return max(count,maxcount);
}