forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
most-common-word.cpp
30 lines (29 loc) · 897 Bytes
/
most-common-word.cpp
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
// Time: O(m + n), m is the size of banned, n is the size of paragraph
// Space: O(m + n)
class Solution {
public:
string mostCommonWord(string paragraph, vector<string>& banned) {
unordered_set<string> lookup(banned.cbegin(), banned.cend());
unordered_map<string, int> counts;
string word;
for (const auto& c : paragraph) {
if (isalpha(c)) {
word.push_back(tolower(c));
} else if (!word.empty()) {
++counts[word];
word.clear();
}
}
if (!word.empty()) {
++counts[word];
}
string result;
for (const auto& kvp : counts) {
if ((result.empty() || kvp.second > counts[result]) &&
!lookup.count(kvp.first)) {
result = kvp.first;
}
}
return result;
}
};