Algorithm


Problem Name: 819. Most Common Word

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:

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:

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.

Code Examples

#1 Code Example with C++ Programming

Code - C++ Programming


class Solution {
public:
    string mostCommonWord(string paragraph, vector<string>& banned) {
        unordered_mapm;
        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;  
    }
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
paragraph = "Bob hit a ball, the hit BALL flew far after it was hit.", banned = ["hit"]

Output

x
+
cmd
"ball"

#2 Code Example with Java Programming

Code - Java Programming


class Solution {
    public static String mostCommonWord(String paragraph, String[] banned) {
        paragraph = paragraph.toLowerCase();
        List < String> bannedWords = Arrays.asList(banned);

        String[] words = paragraph.trim().split("\\s+");
        Map < String, Integer> map = new LinkedHashMap<>();
        int maxValue = Integer.MIN_VALUE;

        for (String word : words) {

            if (!Character.isAlphabetic(word.charAt(word.length()-1))) {
                word = word.substring(0, word.length()-1);
            }

            if (!(word.equals(" ") || word.equals("")) && bannedWords.indexOf(word) == -1) {
                map.put(word, map.getOrDefault(word, 0) + 1);
                maxValue = Math.max(maxValue, map.get(word));
            }
        }

        for (String word : map.keySet()) {
            if (map.get(word) == maxValue) {
                return word;
            }
        }

        return "";
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
paragraph = "Bob hit a ball, the hit BALL flew far after it was hit.", banned = ["hit"]

Output

x
+
cmd
"ball"

#3 Code Example with Javascript Programming

Code - Javascript Programming


const mostCommonWord = function(paragraph, banned) {
    const str = paragraph.toLowerCase()
    const arr = str.replace(/\W+/g, ' ').trim().split(' ')
    const hash = {}
    for(let el of arr) {
        if(banned.indexOf(el) !== -1) {

        } else {
           if(hash.hasOwnProperty(el)) {
              hash[el] += 1
           } else {
               hash[el] = 1
           }
        }
    }
    const res = Object.entries(hash).sort((a, b) => b[1] - a[1])
    return res[0][0]
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
paragraph = "a.", banned = []

Output

x
+
cmd
"a"

#4 Code Example with Python Programming

Code - Python Programming


class Solution:
    def mostCommonWord(self, paragraph, banned):
        """
        :type paragraph: str
        :type banned: List[str]
        :rtype: str
        """
        paragraph = re.findall(r"\u005Cw+", paragraph)
        dic = {}
        mx = [0, 0]
        for char in paragraph:
            char = char.lower()
            if char not in banned:
                if char not in dic: dic[char] = 1
                else: dic[char] += 1
                mx[0] = max(mx[0], dic[char])
                if mx[0] == dic[char]: mx[1] = char
        return mx[1]
        
Copy The Code & Try With Live Editor

Input

x
+
cmd
paragraph = "a.", banned = []

Output

x
+
cmd
"a"

#5 Code Example with C# Programming

Code - C# Programming


using System;
using System.Collections.Generic;

namespace LeetCode
{
    public class _0819_MostCommonWord
    {
        public string MostCommonWord(string paragraph, string[] banned)
        {
            var split = paragraph.Replace('!', ' ').Replace('?', ' ').Replace('\'', ' ').Replace(',', ' ').Replace(';', ' ').Replace('.', ' ').ToLower().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            var bannedSet = new HashSet < string>(banned);
            var counts = new Dictionary();
            foreach (var word in split)
            {
                if (bannedSet.Contains(word))
                    continue;
                if (counts.ContainsKey(word))
                    counts[word]++;
                else
                    counts[word] = 1;
            }

            var max = 0;
            var result = string.Empty;
            foreach (var pair in counts)
            {
                if (max  <  pair.Value)
                {
                    max = pair.Value;
                    result = pair.Key;
                }
            }

            return result;
        }
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
paragraph = "Bob hit a ball, the hit BALL flew far after it was hit.", banned = ["hit"]

Output

x
+
cmd
"ball"
Advertisements

Demonstration


Previous
#818 Leetcode Race Car Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#820 Leetcode Short Encoding of Words Solution in C, C++, Java, JavaScript, Python, C# Leetcode