我这里所说的longest common substring问题和算法导论中的不一样,主要是找出连续的最长子序列。
输入:string S1,S2
输出:所有连续的最长子序列
#include
<
iostream
>
#include < string >
using namespace std;
void Pre_Process( string P, int * pi)
... {
int m=P.size();
pi[0]=0;
int j=0;
int i;
for(i=1;i<m;++i)
...{
while(j>0&&(P[j]!=P[i]))
j=pi[j-1];
if(P[j]==P[i])
++j;
pi[i]=j;
}
}
bool Check( string S, string P)
... {
int n=S.size();
int m=P.size();
int* pi=new int[m];
Pre_Process(P,pi);
int q=0;
int i;
for(i=0;i<n;++i)
...{
while(q>0&&(P[q]!=S[i]))
q=pi[q-1];
if(P[q]==S[i])
++q;
if(q==m)
...{
delete[] pi;
return true;
}
}
delete[] pi;
return false;
}
void find_LCS( string S1, string S2)
... {
int len=S2.size();
int step=len;
bool flag=false;
while(step>=0)
...{
int i;
for(i=0;i<=len-step;++i)
...{
string temp(S2, i, step);
if(Check(S1,temp))
...{
cout<<temp<<endl;
flag=true;
}
}
if(flag)
...{
cout<<"the length of the longest common substring is:"<<step<<endl;
break;
}
else
--step;
}
}
void LCS( string S1, string S2)
... {
if(S1.size()<S2.size())
find_LCS(S2,S1);
else
find_LCS(S1,S2);
}
int main()
... {
string S1("hello world");
string S2("world,hello");
LCS(S1,S2);
return 0;
}
#include < string >
using namespace std;
void Pre_Process( string P, int * pi)
... {
int m=P.size();
pi[0]=0;
int j=0;
int i;
for(i=1;i<m;++i)
...{
while(j>0&&(P[j]!=P[i]))
j=pi[j-1];
if(P[j]==P[i])
++j;
pi[i]=j;
}
}
bool Check( string S, string P)
... {
int n=S.size();
int m=P.size();
int* pi=new int[m];
Pre_Process(P,pi);
int q=0;
int i;
for(i=0;i<n;++i)
...{
while(q>0&&(P[q]!=S[i]))
q=pi[q-1];
if(P[q]==S[i])
++q;
if(q==m)
...{
delete[] pi;
return true;
}
}
delete[] pi;
return false;
}
void find_LCS( string S1, string S2)
... {
int len=S2.size();
int step=len;
bool flag=false;
while(step>=0)
...{
int i;
for(i=0;i<=len-step;++i)
...{
string temp(S2, i, step);
if(Check(S1,temp))
...{
cout<<temp<<endl;
flag=true;
}
}
if(flag)
...{
cout<<"the length of the longest common substring is:"<<step<<endl;
break;
}
else
--step;
}
}
void LCS( string S1, string S2)
... {
if(S1.size()<S2.size())
find_LCS(S2,S1);
else
find_LCS(S1,S2);
}
int main()
... {
string S1("hello world");
string S2("world,hello");
LCS(S1,S2);
return 0;
}
输出结果为:
world
hello
the length of the longest common substring is:5
Press any key to continue