题解 | #单词识别#仿函数Compare+哈希表+优先级队
单词识别
https://www.nowcoder.com/practice/16f59b169d904f8898d70d81d4a140a0
#include <iostream>
#include <unordered_map>
#include <utility>
#include <string>
#include <queue>
#include <unordered_map>
#include <vector>
using namespace std;
int main()
{
// 仿函数比较,建大堆,返回小于的比较(孩子比较父亲)
struct Compare
{
bool operator()(const pair<string, int>& p1, const pair<string, int>& p2)
{
return p1.second < p2.second || (p1.second == p2.second && p1.first > p2.first);
}
};
string s;
getline(cin, s);
vector<string> word;
string tmp;
for (size_t i = 0; i < s.size(); ++i) {
if(s[i] != ' ' && s[i] != '.')
{
tmp += tolower(s[i]);
}
else {
if(tmp.size() >= 1)
word.push_back(tmp);
tmp.clear();
}
}
// 创建一个哈希表
unordered_map<string, int> hash;
for(auto e : word)
{
hash[e]++;
}
// 创建优先级队列
priority_queue<pair<string, int>, vector<pair<string, int>>, Compare> q(hash.begin(), hash.end(), Compare());
for(size_t i = 0; i < hash.size(); ++i)
{
cout << q.top().first << ":" << q.top().second << endl;
q.pop();
}
}
// 64 位输出请用 printf("%lld")

