■ 题目描述
【全量和已占用字符集】
给定两个字符集合,一个是全量字符集,一个是已占用字符集,已占用字符集中的字符不能再使用。
要求输出剩余可用字符集。
输入描述
输出描述
示例1 输入输出示例仅供调试,后台判题数据一般不包含示例
输入
a:3,b:5,c:2@a:1,b:2
输出
a:2,b:3,c:2
说明:
全量字符集为三个a,5个b,2个c
已占用字符集为1个a,2个b
由于已占用字符不能再使用
因此剩余可用字符为2个a,3个b,2个c
因此输出a:2,b:3,c:2
C++代码实现一:
#include
using namespace std;
string s;
int vis[52] = {0};
int ans;
string num;
bool flag = false;
int main()
{
cin >> s;
for(int i = 0; i < s.size(); i ++) {
if(islower(s[i])) ans = s[i] - 'a';
else if(isupper(s[i])) ans = 26 + s[i] - 'A';
else if(isalpha(s[i])) num.push_back(s[i]);
if(s[i] == ',' || s[i] == '@' || i == s.size() - 1) {
if(!flag) vis[ans] = atoi(num.c_str());
else vis[ans] -= atoi(num.c_str());
num.clear();
if(s[i] == '@') flag = true;
}
}
char c = 0;
for(int i = 0; i < 52; i ++) {
if(vis[i] <= 0) continue;
if(i < 26) c = 'a' + i;
else c = 'A' + (i - 26);
if(i > 0) printf(",");
printf("%c:%d",c,vis[i]);
}
return 0;
}
C++代码实现二:
#include
using namespace std;
int main() {
// 处理输入
string input_str;
cin >> input_str;
// 找@符号, 因为一定会存在,所以不用判断是否能找到了
int found_0 = input_str.find("@");
if (found_0 == input_str.size() - 1) {
cout << input_str.substr(0, found_0);
return 0;
}
//处理前半部分
string first_part = input_str.substr(0, found_0);
vector all;
while (first_part.find(",") != string::npos) {
int found = first_part.find(",");
all.push_back(first_part.substr(0, found));
first_part = first_part.substr(found + 1);
}
all.push_back(first_part);
//处理后半部分
string second_part = input_str.substr(found_0 + 1);
vector used;
while (second_part.find(",") != string::npos) {
int found = second_part.find(",");
used.push_back(second_part.substr(0, found));
second_part = second_part.substr(found + 1);
}
used.push_back(second_part);
//保存后半部分已使用的个数
map used_count;
for (int i = 0; i < used.size(); i++) {
int found_1 = used[i].find(":");
if (used_count.find(used[i].substr(0, found_1)) == used_count.end()) {
used_count[used[i].substr(0, found_1)] = stoi(used[i].substr(found_1 + 1));
} else {
used_count[used[i].substr(0, found_1)] += stoi(used[i].substr(found_1 + 1));
}
}
for (int i = 0; i < all.size(); i++) {
int found_1 = all[i].find(":");
if (used_count.find(all[i].substr(0, found_1)) == used_count.end()) {
cout << all[i];
} else {
cout << all[i].substr(0, found_1 + 1)
<< stoi(all[i].substr(found_1 + 1)) - used_count[all[i].substr(0, found_1)];
}
if (i != all.size() - 1) {
cout << ",";
}
}
return 0;
}