華爲筆試題:全量字符集與已佔用字符集

輸入描述

輸入一個字符串,字符串中包含了全量字符集和已佔用字符集,兩個字符集用@相連。@前的字符集合爲全量字符集,@後的字符集爲已佔用字符集合。已佔用字符集中的字符一定是全量字符集中的字符。
字符集中的字符跟字符之間使用英文逗號分隔。字符集中的字符表示爲字符加數字,字符跟數字使用英文冒號分隔,比如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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章