【华为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; }
相关文章推荐
- Android 图片三级缓存之内存缓存(告别软引用(SoftRefrerence)和弱引用(WeakReference))
- 基于zabbix API添加监控主机
- HTTPS的证书未经权威机构认证的情况下,访问HTTPS站点的两种方法
- 二叉树的递归遍历
- 网络应用层——http协议
- ScheduledExecutorService定时周期执行指定的任务
- hdu 1867 A + B for you again
- Java之Exception
- 浅析python 中__name__ = '__main__' 的作用
- OC NSFileManager
- js框架
- Ceph:一种可扩展,高性能的分布式文件系统
- Unsupported major.minor version 51.0解决
- [Leetcode]Single Number III
- 2014阿里前端笔试题(关于弹性盒布局的实现)
- hdu2841(容斥原理)
- vijos - P1494杨辉三角形中的偶数个数 (递归分治 + 记忆化搜索 + python)
- poj--1062(最短路径+枚举)
- openCV—Python(11)—— 图像边缘检测
- IOS-笔记6(拓展,协议)