网上实在找不到一个C++写的LCString算法,就自己写了一个
string LCSubstring(string a, string b)接收两个string,输出长度和string
LCS数组第一列和第一行都置0空出来简化算法,算法的详细设计网上都有,这里就不多说
#include <iostream>
#include <string>
using namespace std;
string LCSubstring(string a, string b){
int length = 0;
int index = 0;
int m = a.size();
int n = b.size();
int **LCS = new int *[m+1];
for(int i=0; i<m+1; i++){
LCS[i] = new int[n+1];
}//pre
for(int i=0; i<m+1; i++){
for(int j=0; j<n+1; j++){
if(i==0 || j==0) LCS[i][j] = 0;
else if(a[i-1]==b[j-1]){
LCS[i][j] = LCS[i-1][j-1]+1;
if(length < LCS[i][j]){
length = LCS[i][j];
index = i;
}
}
else LCS[i][j] = 0;
}
}//dynamic plan
cout<<"length is "<<length<<endl;
return string(a,index-length,length);
}
int main(){
string a = "nopehellodayweqfasdgregqfasdgasdasdasdrehgqfdfweerqweewr";
string b = "asdfdgrrhrethdfsbrthrasdasdathewrgtqgdfsgertqfaafewwqfhelloworld";
cout<<LCSubstring(a,b)<<endl;
return 0;
}