Categories:

Tags:



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.

Constraints

  • 1 <= paragraph.length <= 1000
  • paragraph consists of English letters, space ' ', or one of the symbols: "!?',;.".
  • 0 <= banned.length <= 100
  • 1 <= banned[i].length <= 10
  • banned[i] consists of only lowercase English letters.

Solution

The problem Most Common Word can be solved by counting the number of appearances for each word using a hash map. Then, the one that appeared the most without being banned can be found using a hash set.

Implementation

static const int fast_io = []()
{
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    return 0;
}();

class Solution
{
  public:
    string mostCommonWord(string paragraph, vector<string> &banned)
    {
        unordered_set<string> ban(banned.begin(), banned.end());
        unordered_map<string, int> hashmap;

        string word;
        paragraph += ' ';

        for (int i = 0; i < paragraph.length(); i++)
        {
            if (isalpha(paragraph[i]))
                word += tolower(paragraph[i]);
            else if (word.length())
            {
                hashmap[word] += 1;
                word = "";
            }
        }

        string ret = "";
        for (auto &[key, val] : hashmap)
            if (ban.find(key) == ban.end() && hashmap[ret] < val)
                ret = key;

        return ret;
    }
};