题目描述:
给定两个字符集合,一个为全量字符集,一个为已占用字符集。已占用的字符集中的字符不能再使用,要求输出剩余可用字符集。
输入描述:
输入为一个字符串,字符串中包含了全量字符集合已占用字符集,两个字符集使用@连接。@前的字符集合为全量字符集,@后的字符集合为已占用字符集。
输入:
a:3,b:5,c:2@a:1,b:2
输出:
a:2,b:3,c:2
核心代码如下:
#include <iostream>
#include <string>
#include <map>
#include <sstream>
#include <algorithm>
using namespace std;
bool isNum(char ch)
{
return ch <= '9' && ch >= '0';
}
int main()
{
map<char, int> cnt1, cnt2;
string s;
string str;
cin >> s;
bool flag = true;
for (int i = 0; i<s.size(); i++)
{
if (s[i] == ',')
continue;
else if (s[i] == '@')
{
flag = false;
continue;
}
if (flag) //@之前部分
{
string num_str;
char ch = s[i];
str += s[i];
num_str = s.substr(i + 2, 1);
i += 2;
while (isNum(s[i + 1]))
{
num_str = num_str + s.substr(i + 1, 1);
i++;
}
int num = 0;
stringstream ss(num_str);
ss >> num; //将ss输出给num
//cout << ch << " " << num << endl;
cnt1.insert(make_pair(ch, num));
}
else //@之后部分
{
string num_str;
char ch = s[i];
num_str = s.substr(i + 2, 1);
i += 2;
while (i + 1 < s.size() && isNum(s[i + 1])) //i + 1 < s.size()边界条件很重要,不然会内存越界
{
num_str = num_str + s.substr(i + 1, 1);
i++;
}
int num = 0;
stringstream ss(num_str);
ss >> num; //将ss输出给num
//cout << ch << " " << num << endl;
cnt2.insert(make_pair(ch, num));
}
//i++;
}
//cout << str << endl;
for (map<char, int>::iterator it = cnt2.begin(); it != cnt2.end(); it++)
{
char ch = it->first;
int n = it->second;
cnt1[ch] -= n;
}
//cout << str << endl;
flag = true;
map<char, int>::iterator it;
for (int i = 0; i<str.size(); i++)
{
it = cnt1.find(str[i]);
if (it->second != 0)
{
if (flag)
{
cout << it->first << ":" << it->second;
flag = false;
}
else
cout << "," << it->first << ":" << it->second;
}
}
cout << endl;
return 0;
}