您的位置:首页 > 其它

【华为OJ平台练习题】求最大公共子串的个数和元素

2015-08-18 17:28 411 查看

1.原题是求出最大公共子串的个数即可

原理:利用二维矩阵排列的方式,将俩字符串进行比较

#include <iostream>
#include <vector>
using namespace std;

int  prcs_2Strs(const char* s1,const char* s2)
{
int maxSameLength = 0;
int L1 = strlen(s1);
int L2 = strlen(s2);
if(L1==0 || L2==0)	//判断字符串是否为空?
return 0;

int **c = new int*[L1+1];  //创建矩阵,保存S1与S2各元素比较的结果
for(int i = 0; i < L1+1; i++)
c[i] = new int[L2+1];
for(int i = 0; i < L1+1; i++)  //矩阵初始化为0
{
for(int j = 0; j < L2+1; j++)
{	c[i][j]=0;     }
}
for(int m =0;m<L1;m++)
{
for(int n=0;n<L2;n++)
{
if(s1[m]==s2
)	//开始比较
{
//统计比较结果在矩阵 C 中
if((m==0||n==0))	//第一行或者第一列,C[m]
没有左上角元素,则把它自己置为1
c[m]
=1;
else
c[m]
=c[m-1][n-1]+1;	//在左上角元素基础上加上1
}
}
}
for(int i = 0; i < L1+1; i++)  //找出最大值,赋给maxSameLength
{
for(int j = 0; j < L2+1; j++)
{
if(c[i][j]>maxSameLength)
maxSameLength = c[i][j];
}
}
return maxSameLength;
}

int main()
{
char s1[30],s2[30];
cout<<"输入俩字符串:";
cin.getline(s1,30);
cin.getline(s2,30);
cout<<"最大公共子串元素数量为:"<<prcs_2Strs(s1,s2)<<endl;
return 0;
}




2. 统计个数并输出元素

我的思路是将个数和位置存入到一个Vector中,然后输出

#include <iostream>
#include <vector>
using namespace std;

vector<int>  prcs_2Strs(const char* s1,const char* s2)
{
vector<int> pos;
int maxSameLength = 0;
int L1 = strlen(s1);
int L2 = strlen(s2);
if(L1==0 || L2==0)	//判断字符串是否为空
return pos;

int **c = new int*[L1+1];  //创建矩阵,保存S1与S2各元素比较的结果
for(int i = 0; i < L1+1; i++)
c[i] = new int[L2+1];
for(int i = 0; i < L1+1; i++)  //矩阵初始化为0
{
for(int j = 0; j < L2+1; j++)
{	c[i][j]=0;     }
}

for(int m =0;m<L1;m++)
{
for(int n=0;n<L2;n++)
{
if(s1[m]==s2
)	//开始比较
{
//统计比较结果在矩阵 C 中
if((m==0||n==0))	//第一行或者第一列,C[m]
没有左上角元素,则把它自己置为1
c[m]
=1;
else
c[m]
=c[m-1][n-1]+1;	//在左上角元素基础上加上1
}
}
}
for(int i = 0; i < L1+1; i++)  //找出最大值,赋给maxSameLength
{
for(int j = 0; j < L2+1; j++)
{
if(c[i][j]>maxSameLength)
maxSameLength = c[i][j];
}
}
pos.push_back(maxSameLength);

for(int i = 0; i < L1+1; i++)  //找出最大值的位置
{
for(int j = 0; j < L2+1; j++)
{
if(c[i][j]==maxSameLength)
pos.push_back(i);
}
}
return pos;	//最终pos中记录了最大公共子串的长度和在S1中位置
}

int main()
{
char s1[30],s2[30];
cout<<"输入俩字符串:";
cin.getline(s1,30);
cin.getline(s2,30);
vector<int> results = prcs_2Strs(s1,s2);
int num = results[0];
int posEnd = results[1];
if(num>0)
{
cout<<"最大公共子串元素数量为:"<<num<<endl;
cout<<"最大公共子串元素:";
for(int a=1;a<=num;a++)
cout<<s1[posEnd-num+a];
}
return 0;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: