我这里所说的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;
}
输出结果为:
world
hello
the length of the longest common substring is:5
Press any key to continue
本文介绍了一种寻找两个字符串间最长公共子串的算法。通过逐步减少子串长度并检查是否存在,最终找到最长的公共子串。代码示例展示了如何实现这一过程。
307

被折叠的 条评论
为什么被折叠?



