-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmostCommonWord.cpp
More file actions
28 lines (27 loc) · 884 Bytes
/
mostCommonWord.cpp
File metadata and controls
28 lines (27 loc) · 884 Bytes
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
// Source: https://leetcode.com/problems/most-common-word/
// Author: Miao Zhang
// Date: 2021-03-14
class Solution {
public:
string mostCommonWord(string paragraph, vector<string>& banned) {
unordered_set<string> b(banned.begin(), banned.end());
unordered_map<string, int> counts;
const string pattern = "!?',;. ";
int best = 0;
string res = "";
int n = paragraph.size();
string word;
for (int i = 0; i <= n; i++) {
if (i == n || pattern.find(paragraph[i]) != string::npos) {
if (++counts[word] > best && !b.count(word) && word.size() > 0) {
best = counts[word];
res = word;
}
word.clear();
} else {
word += tolower(paragraph[i]);
}
}
return res;
}
};