forked from lzl124631x/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
s1.cpp
36 lines (36 loc) · 1.13 KB
/
s1.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
31
32
33
34
35
36
// OJ: https://leetcode.com/problems/most-common-word/
// Author: github.com/lzl124631x
// Time: O(N) where N is character count in paragraph
// Space: O((B + P)W)
// where B is the size of ban list,
// P is unique count of words in paragraph that are not banned,
// and W is average word length
class Solution {
private:
string getWord(string::iterator& it, string::iterator end) {
while (it != end && !isalpha(*it)) ++it;
string res;
for (; it != end && isalpha(*it); ++it) {
res += tolower(*it);
}
return res;
}
public:
string mostCommonWord(string paragraph, vector<string>& banned) {
unordered_map<string, int> m;
unordered_set<string> ban(banned.begin(), banned.end());
string word;
string res;
int maxCnt = 0;
auto it = paragraph.begin();
while ((word = getWord(it, paragraph.end())) != "") {
if (ban.find(word) != ban.end()) continue;
m[word]++;
if (m[word] > maxCnt) {
maxCnt = m[word];
res = word;
}
}
return res;
}
};