Most Common Word Problem


Description

LeetCode Problem 819.

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.

Example 1:

1
2
3
4
5
6
7
8
Input: paragraph = "Bob hit a ball, the hit BALL flew far after it was hit.", banned = ["hit"]
Output: "ball"
Explanation: 
"hit" occurs 3 times, but it is a banned word.
"ball" occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph. 
Note that words in the paragraph are not case sensitive,
that punctuation is ignored (even if adjacent to words, such as "ball,"), 
and that "hit" isn't the answer even though it occurs more because it is banned.

Example 2:

1
2
Input: paragraph = "a.", banned = []
Output: "a"

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.


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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;  
    }
};




Related Posts

X Of A Kind In A Deck Of Cards Problem

LeetCode 914. In a deck of cards, each card has...

Word Subsets Problem

LeetCode 916. You are given two string arrays words1 and...

Vowel Spellchecker Problem

LeetCode 966. Given a wordlist, we want to implement a...

Verifying An Alien Dictionary Problem

LeetCode 953. In an alien language, surprisingly, they also use...

Unique Morse Code Words Problem

LeetCode 804. International Morse Code defines a standard encoding where...

Unique Email Addresses Problem

LeetCode 929. Every valid email consists of a local name...