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

时间:2023-03-09 00:19:10
【华为OJ平台练习题】求最大公共子串的个数和元素

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[n]) //開始比較
{
//统计比較结果在矩阵 C 中
if((m==0||n==0)) //第一行或者第一列,C[m][n]没有左上角元素,则把它自己置为1
c[m][n]=1;
else
c[m][n]=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;
}

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

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />

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[n]) //開始比較
{
//统计比較结果在矩阵 C 中
if((m==0||n==0)) //第一行或者第一列,C[m][n]没有左上角元素,则把它自己置为1
c[m][n]=1;
else
c[m][n]=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;
}

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