Most Common Word LeetCode solution in C++

1
class Solution {
2
public:
3
string mostCommonWord(string paragraph, vector<string> &banned) {
4
string temp;
5
vector<string> words;
6
for (char c : paragraph) {
7
if (isalpha(c) && !isspace(c))
8
temp += tolower(c);
9
else {
10
if (temp.length()) words.push_back(temp);
11
temp = "";
12
}
13
}
14
if (temp.length()) words.push_back(temp);
15

16
map<string, int> mp;
17
for (string i : words) mp[i]++;
18
for (string i : banned) mp[i] = 0;
19
string ans;
20
int maxUsedFreq = 0;
21
for (auto i : mp) {
22
if (i.second > maxUsedFreq) {
23
ans = i.first;
24
maxUsedFreq = i.second;
25
}
26
}
27
return ans;
28
}
29
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0