-
Notifications
You must be signed in to change notification settings - Fork 0
/
most_frequent_word.cc
57 lines (48 loc) · 1.64 KB
/
most_frequent_word.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class Solution {
public:
string mostCommonWord(string paragraph, vector<string>& banned) {
unordered_map<string, int> ht;
unordered_set<string> banned_ht;
string word;
string most_common;
int max_freq = 0;
// use a ht for banned words for little optimization
for (auto w : banned)
if (banned_ht.find(w) == banned_ht.end())
banned_ht.emplace(w);
for (auto c : paragraph) {
if (isalpha(c))
// build word
word += std::tolower(c);
else if (isspace(c) || ispunct(c)) {
if (word.empty()) continue;
if (banned_ht.find(word) != banned_ht.end()) {
// Found a word that's banned, invalidate and move on
word.clear();
continue;
}
if (ht.find(word) == ht.end())
ht.emplace(word, 1);
else
ht.find(word)->second++;
word.clear();
}
}
// Proceed to add the last word processed if it isn't banned
if (!word.empty() && (banned_ht.find(word) == banned_ht.end())) {
if (ht.find(word) == ht.end())
ht.emplace(word, 1);
else
ht.find(word)->second++;
}
most_common = ht.begin()->first;
max_freq = ht.begin()->second;
for (auto w : ht) {
if (w.second > max_freq) {
max_freq = w.second;
most_common = w.first;
}
}
return most_common;
}
};