1、有3个字母a,b,c:你输入一个数字,要输出所有的组合字符和组合数
举例:输入1 输出a,b,c 3
输入2 输出aa,ab,ac,ba,bb,bc,ca,cb,cc 9
代码:(我稍微修改了一下,使得程序可以输入任意字母)
#include<bits/stdc++.h>
using namespace std;
//只要求一个字母时,拆分即可
vector<string> cal(string a){
vector<string> res;
for(int i = 0;i < a.length();i++){
string temp = "";
temp += a[i];
res.push_back(temp);
}
return res;
}
// 要求多个字母时,循环笛卡尔积
vector<string> cal(vector<string> a, string b){
vector<string> res;
for(int i = 0;i < a.size();i++){
for(int j = 0;j < b.length();j++){
string temp = "";
temp += a[i];
temp += b[j];
res.push_back(temp);
}
}
return res;
}
void show(vector<string> res){
for(int i = 0;i < res.size();i++){
cout<<res[i]<<" ";
}
cout<<res.size()<<endl;
}
int main(){
string a;
cout<<"输入字符串"<<endl;
cin>>a;
int n;
cout<<"输入数字"<<endl;
cin>>n;
vector<string> res = cal(a);
if(n == 1){
show(res);
} else {
while(--n){
res = cal(res, a);
}
show(res);
}
}
2、求字符串1与字符串2的最大公共子串的长度及此长度最大公共子串的个数。
输入 abcdefg (最大公共子串:bcd)
Eebcdfg
输出 3 1
输入 abcdefg (最大公共子串为:abcd defg)
abcddefg
输出 4 2
#include<bits/stdc++.h>
#include<string>
using namespace std;
//返回a中b的个数
//应该可以用自带的count函数实现
int count(string a, string b){
int sum = 0;
for(int i = 0;i < a.length();i++){
for(int j = i + 1;j <= a.length();j++){
string temp = a.substr(i, j - i);
if(temp == b)
sum++;
}
}
return sum;
}
int main(){
string a, b;
cin>>a>>b;
int maxl = 0,num = 0; //maxl 记录最长字符串的长度,num记录最长字符串的个数
for(int i = 0;i < a.length();i++){
for(int j = i + 1;j <= a.length();j++){
string temp = a.substr(i, j - i);
int len = temp.length();
if(count(b, temp) == 0)
continue;
if(maxl < len){
maxl = len;
num = 1;
} else if(maxl == len){
num++;
}
}
}
cout<<maxl<<" "<<num;
}