69,373
社区成员
发帖
与我相关
我的任务
分享
#include <cstring>
#include <iostream>
using namespace std;
void LCS(string str1,string str2)
{
int m=str1.length ();
int n=str2.length ();
int R[15][15]={0}; //用来记录匹配情况
int max=0;
int end=0;
for(int x=0;x<m; x++)
{
for(int y=0;y < n; y++)
{
if(str1[x]==str2[y])
{
if(x==0||y==0)
{
R[x][y]=1;
}
else
{
R[x][y]=R[x-1][y-1]+1;
}
}
if(R[x][y]>max)
{
max=R[x][y];
end=y;
}
}
}
int start=end-max+1;
for(int i=start;i<=end;i++)
{
cout<<str2[i];
}
}
int main()
{
string str1="abcdef"; //要比较的两个字符串
string str2="rraijdef";
LCS(str1,str2);
cout << endl;
system("pause");
}
仅供参考char * findMaxLength( char *p2, char *p3)
{
char *pS = NULL; // 短串
char *pL = NULL; // 长串
size_t n2 = strlen(p2);
size_t n3 = strlen(p3);
size_t n = 0;
if ( n2 > n3)
{
pS = p3;
pL = p2;
n = n3;
}
else
{
pS = p2;
pL = p3;
n = n2;
}
char *p = new char[n+1]; // 结果字符串
p[n] = '\0';
strncpy(p ,pS ,n);
if (strstr(pL ,p)) // 先比较整个
{
printf("%s\n" ,p);
}
else
{
p[0] = '\0'; // 细节处理,防止没有匹配到后返回整个短字符串
for (int i = n; i != 0 ;--i)
{
p[i] = '\0';
for (int j = 0; j != n-i+1; ++j)
{
memcpy(p ,pS+j ,i);
if (strstr(pL ,p))
{
// printf("%s\n" ,p); // 打印出来看看,调用者负责释放该空间
return p;
}
}
}
}
}
int main(int argc, _TCHAR* argv[])
{
char str1[] = "sbcdefiads";
char str2[] = "rrrrabcdefijdef";
char *p = findMaxLength(str1 ,str2);
printf("%s\n" ,p);
return 0;
}