2015年北理复试上机题

本文介绍了一种算法,用于生成给定字符串的n次笛卡尔积组合,并提出了解决两个字符串最大公共子串及其数量的问题。通过C++代码实现,展示了如何计算字符串的所有可能组合,以及找到两个字符串间最长的共享子串及其出现次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值