中兴笔试

问题:给定两个字符串(包含大小写字符),选出两个字符串的公共字符(不区分大小写),然后从公共字符中选出指定个数的字符,总共有多少种选法,输出所有结果,每个结果字典排序

如:AbadfHTr , eaDJhIR,公共字符为adhr,指定个数为3,输出adh adr ahr dhr

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

//从n个字符中选m个字符进行组合即C(n,m)
void combination(const char* ptr, int pass_len, vector<char>& result) {
	if(ptr == nullptr || (*ptr == '\0' && pass_len != 0))
		return;
	

	if (pass_len == 0) {
		for (auto i = 0; i < result.size(); ++i)
			cout << result[i];
		cout << endl;
		return;
	}
	result.push_back(*ptr);
	combination(ptr + 1, pass_len - 1, result);
	result.pop_back();

	combination(ptr + 1, pass_len, result);

}

void make_password(string& str1, string& str2, int pass_len) {
	set<char> set1(str1.begin(), str1.end());
	set<char> set2(str2.begin(), str2.end());
	set<char> set_inter;
	
	auto set1_it = set1.begin();
	for (; set1_it != set1.end(); ++set1_it) {
		auto pos = set2.find(*set1_it);
		if (pos != set2.end())
			set_inter.insert(*set1_it); //set_inter里包含a d h r
	}

	
	string s(set_inter.begin(), set_inter.end());
	const char* arr = s.c_str();
	vector<char> result;
	combination(arr, pass_len, result);
}

int main() {
	string str1("AbadfHTr");
	string str2("eaDJhIR");
	for (auto& ch : str1) {
		if (ch >= 'A' && ch <= 'Z')
			ch = tolower(ch);
	}
	for (auto& ch : str2) {
		if (ch >= 'A' && ch <= 'Z')
			ch = tolower(ch);
	}
	int pass_len = 3;
	make_password(str1, str2, pass_len);

	system("pause");
}

猜你喜欢

转载自blog.csdn.net/weixin_40804971/article/details/82587271