华为 4.15号笔试
菜鸡一枚,只做了前两题,而且都没有完全AC。下面代码仅供参考,会有一些测试用例没有考虑到,希望大家帮忙指正。
第一题:
统计投票个数,返回投票最多的人名,相同的话,字典序在前面的优先。
输入:
Lily,Tom,Lucy,Lucy,Tim
输出:
Lucy
#include <iostream> #include <string> #include <algorithm> #include <vector> #include <map> using namespace std; bool checkVaild(string str) { if (!(str[0] >= 'A' && str[0] <= 'Z')) { return false; } for (int i = 1; i < str.size(); i++) { if (!(str[i] >= 'a' && str[i] <= 'z')) { return false; } } return true; } string countVal(string str) { int pos; vector<pair<string, int>> result; map<string, int> stats; for (int i = 0; i < str.size(); i++) { pos = str.find(",", i); if (pos < str.size()) { string s = str.substr(i, pos - i); if (!checkVaild(s)) return "error.0001"; if (stats.find(s) != stats.end()) { stats[s]++; } else { stats[s] = 1; } i = pos; } } int maxCount = 0; string tmp; for (auto it = stats.begin(); it != stats.end(); it++) { if (it->second > maxCount) { maxCount = it->second; tmp = it->first; } } return tmp; } int main() { string nameList; while (cin >> nameList) { cout << countVal(nameList) << endl; } //cout << checkVaild("Lucy") << endl; return 0; }
第二题:
字符串分割和匹配。
输入为两个,首先是要匹配的字符串,然后是带有固定格式的字符串,如下:
read[addr=0x17,mask=0xff,val=0x7],read_his[addr=0xff,mask=0xff,val=0x1],read[addr=0xf0,mask=0xff,val=0x80],输出和字符串匹配的组的addr,mask,val值。
如果没有匹配的组,则输出"FAIL",注意回车是"\r\n"。
输入:
read read[addr=0x17,mask=0xff,val=0x7],read_his[addr=0xff,mask=0xff,val=0x1],read[addr=0xf0,mask=0xff,val=0x80]
输出:
0x17 0xff 0x7
0xf0 0xff 0x80
代码:
#include <iostream> #include <string> #include <vector> #include <regex> using namespace std; vector<string> split(const string& in, const string& patt) { vector<string> result; regex re{patt}; return vector<string> { sregex_token_iterator(in.begin(), in.end(), re, -1), sregex_token_iterator() }; } vector<string> matchInfo(string str, string pattern) { int pos; vector<string> rst = split(str, "]"); vector<string> result; for (auto &estr: rst) { if (estr[0] == ',') estr = estr.substr(1, estr.size() - 1); pos = estr.find("["); string forMatch = estr.substr(0, pos); string remainStr = estr.substr(pos + 1, estr.size() - pos); if (forMatch == pattern) { vector<string> rst1 = split(remainStr, ","); for (auto s: rst1) { pos = s.find("="); string val = s.substr(pos + 1, s.size() - pos); result.push_back(val); } } } return result; } int main() { string str; string pattern; while (cin >> pattern >> str) { vector<string> rst = matchInfo(str, pattern); if (rst.empty()) cout << "FAIL\r\n"; else { int count = 0; for (auto r: rst) { if (count < 2) { cout << r << " "; count++; } else { cout << r << "\r\n"; count = 0; } } } } return 0; }#华为春招##华为##笔试题目#