Skip to main content

Most Common Word

Problem

Given a string paragraph and a string array of the banned words banned, return the most frequent word that is not banned. It is guaranteed there is at least one word that is not banned, and that the answer is unique.

The words in paragraph are case-insensitive and the answer should be returned in lowercase.

Solution Approach

Expected Time Complexity: O(n)O(n)

Click - to see solution code
class Solution {
public:
string mostCommonWord(string paragraph, vector<string>& banned) {
unordered_map<string, int>m;
for(int i = 0; i < paragraph.size();){
string s = "";
while(i < paragraph.size() && isalpha(paragraph[i])) s.push_back(tolower(paragraph[i++]));
while(i < paragraph.size() && !isalpha(paragraph[i])) i++;
m[s]++;
}
for(auto x: banned) m[x] = 0;
string res = "";
int count = 0;
for(auto x: m)
if(x.second > count) res = x.first, count = x.second;
return res;
}
};