输入描述
输入一个字符串,字符串中包含了全量字符集和已占用字符集,两个字符集用@相连。@前的字符集合为全量字符集,@后的字符集为已占用字符集合。已占用字符集中的字符一定是全量字符集中的字符。
字符集中的字符跟字符之间使用英文逗号分隔。字符集中的字符表示为字符加数字,字符跟数字使用英文冒号分隔,比如a:1,表示1个a字符。
字符只考虑英文字母,区分大小写,数字只考虑正整形,数量不超过100,如果一个字符都没被占用,@标识符仍在,例如a:3,b:5,c:2@
输出描述
可用字符集。输出带回车换行。
示例
输入:a:3,b:5,c:2@a:1,b:2
输出:a:2,b:3,c:2
说明:全量字符集为3个a,5个b,2个c。已占用字符集为1个a,2个b。由于已占用字符集不能再使用,因此,剩余可用字符为2个a,3个b,2个c。因此输出a:2,b:3,c:2。注意,输出的字符顺序要跟输入一致。不能输出b:3,a:2,c:2。如果某个字符已全被占用,不需要输出。例如a:3,b:5,c:2@a:3,b:2,输出为b:3,c:2。
代码
主要操作就是字符串分割
#include<iostream>
#include<string>
#include<algorithm>
#include<stdlib.h>
#include<vector>
#include<assert.h>
using namespace std;
//分割字符串函数
vector<string> split(const string &str, const string &delim)
{
vector<string> res;
if ("" == str)
return res;
char *strs = new char[str.length() + 1];
strcpy(strs, str.c_str());
char *d = new char[delim.length() + 1];
strcpy(d, delim.c_str());
char *p = strtok(strs, d);
while (p)
{
string s = p;
res.push_back(s);
p = strtok(NULL, d);
}
return res;
}
void StringCount(vector<string> str, vector<int> &counts)
{
for (int i = 0; i < str.size(); i++)
{
string num = str[i].substr(2, str[i].length() - 2);
char *nums = new char[num.length() + 1];
strcpy(nums, num.c_str());
int number = atoi(nums);
counts[str[i][0]] = number;
}
}
string CalResString2(string all, string used)
{
string res = "";
vector<string> allStr = split(all, ",");
vector<string> usedStr = split(used, ",");
vector<int> allCounts(256, 0);
vector<int> usedCounts(256, 0);
vector<int> resCounts(256, 0);
StringCount(allStr, allCounts);
StringCount(usedStr, usedCounts);
for (int i = 0; i < 256; i++)
{
resCounts[i] = allCounts[i] - usedCounts[i];
assert(resCounts[i] >= 0);
if (resCounts[i] > 0)
{
char ch = i;
res = res + ch + ":" + to_string(resCounts[i]) + ",";
}
}
res.erase(res.length()-1);//最后一个逗号去掉
return res;
}
int main()
{
string str;
while (cin>>str)
{
string strAll = "";
string used = "";
if (str.find("@")!=string::npos)
{
int index = str.find("@");
strAll = str.substr(0, index);
used = str.substr(index + 1, str.length() - index);
string res = CalResString2(strAll, used);
cout << res << endl;
}
}
return 0;
}