#include<iostream>
using namespace std;
char* LCS(char* left,char* right);
int main(){
char *left,*right;
left = new char[1024];
right = new char[1024];
cout << "please input the first string:";
cin >> left;
cout << "please input the second string:";
cin >> right;
cout << "最长公共子串是:";
cout << LCS(left,right)<<endl;
return 0;
}
char* LCS(char*left,char* right){
int lenLeft,lenRight;
lenLeft = strlen(left);
lenRight = strlen(right);
int *c = new int[lenRight];
int start,end,len;
end = len = 0;
for(int i = 0; i < lenLeft; i++){
for(int j = lenRight-1; j >= 0; j--){
if(left[i] == right[j]){
if(i == 0 || j == 0)
c[j] = 1;
else
c[j] = c[j-1]+1;
}
else
c[j] = 0;
if(c[j] > len){
len = c[j];
end = j;
}
}
}
char *p = new char[len+1];
start = end - len + 1;
for(i = start; i <= end; i++)
p[i - start] = right[i];
p[len] = '/0';
return p;
}
该博客展示了用C++实现最长公共子串算法的代码。通过输入两个字符串,程序能计算并输出它们的最长公共子串。代码包含主函数用于输入处理,以及LCS函数实现具体的算法逻辑。
1万+

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



