我一直试图编写一个程序,计算两个字符串共有的最长公共连续序列(或子字)。代码工作没有任何语法错误,但每次我得到像237743等乱码随机结果,希望有人可以弄清楚我哪里出错了。 例如, 如果我输入第一个单词作为' stack'第二个词是' stackoverflow' ,它应该输出5(常用字=堆栈,长度5),但它给了我' 2752053'
#include <iostream>
using namespace std;
int getlcw(char arr1[],char arr2[])
{
u=sizeof(arr1)/sizeof(arr1[0]);
v=sizeof(arr2)/sizeof(arr2[0]);
if(u==0||v==0)
{ cout<<"fail";
return 0;
}
int lcw[u+1][v+1]; \\1 extra row and column to indicate word has ended , no chance for subword
int maxlcw=0;
for(int i=0;i<u+1;++i) \\intialise last row and col to 0
{
lcw[i][v+1]=0;
}
for(int i=0;i<v+1;++i)
{
lcw[u+1][i]=0;
}
for(int i=u;i>=0;--i)
{
for(int j=v;j>=0;--j)
{
if(arr1[j]==arr2[i])
lcw[i][j]=1+(lcw[i+1][j+1]);
else
lcw[i][j]=0;
if(lcw[i][j]>maxlcw)
maxlcw=lcw[i][j];
}
}
return maxlcw;
}
int main()
{ int x,y;
cout<<"enter size of word 1\n";
cin>>x;
char arr1[x];
cout<<"enter size of word 2\n";
cin>>y;
char arr2[y];
cout<<"word 1\n";
for(int i=0;i<x;++i)
{
cin>>arr1[i];
}
cout<<"word 2\n";
for(int j=0;j<y;++j)
{
cin>>arr2[j];
}
int ans=getlcw(arr1,arr2);
cout<<ans;
cin>>x;
}
这是我从算法中获得想法的链接 -
https://www.iarcs.org.in/inoi/online-study-material/topics/dp-classics.php
答案 0 :(得分:0)
您可以通过两种方式解决它:查看它:
自上而下的方法:
int getlcw(char arr1[],char arr2[])
{
u=sizeof(arr1)/sizeof(arr1[0]);
v=sizeof(arr2)/sizeof(arr2[0]);
if(u==0||v==0)
{ cout<<"fail";
return 0;
}
int lcsw[u+1][v+1]; \\1 extra row and column to indicate word has ended , no chance for subword
int maxlcw=0;
for(int i=0; i<u+1;i++)
{
for(j=0; j<v+1; j++)
{
if(i == j) lcsw[i][j] = 0;
if(arr1[i]!= arr2[j]) lcsw[i][j] = 0;
else
{
lcsw[i][j] = 1+lcsw[i-1][j-1];
maxlcw= max(maxlcw, lcsw[i][j]);
}
}
}
return maxlcw;
}
自下而上当你正在尝试:
int getlcw(char arr1[],char arr2[])
{
u=sizeof(arr1)/sizeof(arr1[0]);
v=sizeof(arr2)/sizeof(arr2[0]);
if(u==0||v==0)
{ cout<<"fail";
return 0;
}
int lcsw[u+1][v+1]; \\1 extra row and column to indicate word has ended , no chance for subword
int maxlcw=0;
for(int i=u;i>=0;i--)
{
for(int j=v;j>=0;j--)
{
if(i == j) lcsw[i][j] = 0;
if(arr1[i]!= arr2[j]) lcsw[i][j] = 0;
else
{
lcsw[i][j] = 1+lcsw[i+1][j+1];
maxlcw= max(maxlcw, lcsw[i][j]);
}
}
}
}