1.题目
给定两个字符串A和B,长度分别为m和n,要求找出它们最长的公共子串,并返回其长度。例如:
A = "HelloWorld"
B = "loop"
则A与B的最长公共子串为 "lo",返回的长度为2。
2.代码
#include <iostream>
#include <string>
#include <stack>
using namespace std;
void LCS(string s1,string s2)
{
int m=s1.length()+1;
int n=s2.length()+1;
int **c;
c=new int* [m];
for(int i=0;i<m;i++)
{
c[i]=new int [n];
}
for(int i=0;i<m;i++)
c[i][0]=0;
for(int i=0;i<n;i++)
c[0][i]=0;
int max= -1;
int x,y;
for(int i=0;i<m-1;i++)
{
for(int j=0;j<n-1;j++)
{
if(s1[i]==s2[j])
{
c[i+1][j+1]=c[i][j]+1;
}
else
c[i+1][j+1]=0;
if (max < c[i+1][j+1])
{
max = c[i+1][j+1];
x = i;
y = j;
}
}
}
// cout << x << " " << y << endl;
char *ss = new char [max];
int k = max - 1;
stack<char> same;
int i = x,j = y;
while( i >=0 && j >=0)
{
if (s1[i] == s2[j])
{ ss[k--] = s1[i];
same.push(s1[i]);
i--;
j--;
}
else
break;
}
cout << "最长公共子串:" << endl;
for (int i = 0;i < max;i++)
cout << ss[i] ;
cout << endl;
while(!same.empty())
{
cout<<same.top();
same.pop();
}
cout << endl << "长度" << endl << max << endl;
for (int i = 0; i<m; i++)
{
delete [] c[i];
}
delete []c;
}
int main()
{
string s1="ABCBDAB";
string s2="BCZBDBA";
LCS(s1,s2);
return 0;
}