华为OD机试【前K个高频单词】
输入:
[“i”,“love”,“leetcode”,“i”,“love”,“coding”]
2
输出:
i
love
解析: “i” 和 “love” 为出现次数最多的两个单词,均为2次。注意,按字母顺序 “i” 在 “love” 之前。
考点 字符串 哈希表
#include <bits/stdc++.h>
using namespace std;
vector<string> split(string str) {//函数用于分割字符串后 将单词存入res数组中
str = str.substr(1, str.size() - 2);
vector<string>res;
while (str.find(',')!=str.npos) {
int p = str.find(',');
string tmp = str.substr(2, p-3);
res.push_back(tmp);
str = str.substr(p+1);
}
res.push_back(str.substr(2,str.size()-4));
return res;
}
void getmax(map<string, int>&mp) {//函数用于找值最大的key并输出
int mx = 0;;
string tmp;
for (auto a : mp) {//找值最大的key
if (a.second > mx) {
mx = a.second;
tmp = a.first;
}
}
cout <<tmp <<endl;//输出key
mp[tmp] = 0;//key对应的值置零
}
int main() {
string s;
map<string, int>mp;
vector<string>init;
getline(cin, s);
int k = 0;
cin >> k;
init = split(s);
for (int i = 0; i < init.size(); i++) {//将res内的单词记录在map中
string b = init[i];
mp[b]++;
}
for (int i = 0; i < k; i++) {//k的值为getmax函数执行次数
getmax(mp);
}
}