Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/819.html

819. Most Common Word (Easy)

Given a paragraph and a list of banned words, return the most frequent word that is not in the list of banned words.  It is guaranteed there is at least one word that isn’t banned, and that the answer is unique.

Words in the list of banned words are given in lowercase, and free of punctuation.  Words in the paragraph are not case sensitive.  The answer is in lowercase.

Example:

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.

Note:

  • 1 <= paragraph.length <= 1000.
  • 1 <= banned.length <= 100.
  • 1 <= banned[i].length <= 10.
  • The answer is unique, and written in lowercase (even if its occurrences in paragraph may have uppercase symbols, and even if it is a proper noun.)
  • paragraph only consists of letters, spaces, or the punctuation symbols !?',;.
  • There are no hyphens or hyphenated words.
  • Words only consist of letters, never apostrophes or other punctuation symbols.

Solution 1.

  • class Solution {
        public String mostCommonWord(String paragraph, String[] banned) {
            paragraph = paragraph.toLowerCase();
            String[] punctuationsArray = {"!", "\\?", "\'", ",", ";", "\\."};
            for (String punctuation : punctuationsArray)
                paragraph = paragraph.replaceAll(punctuation, " ");
            while (paragraph.indexOf("  ") >= 0)
                paragraph = paragraph.replaceAll("  ", " ");
            Set<String> bannedSet = new HashSet<String>();
            for (String word : banned)
                bannedSet.add(word);
            String mostCommonWord = "";
            int maxFrequency = 0;
            Map<String, Integer> wordFrequencyMap = new HashMap<String, Integer>();
            String[] paragraphArray = paragraph.split(" ");
            for (String word : paragraphArray) {
                if (bannedSet.contains(word))
                    continue;
                int frequency = wordFrequencyMap.getOrDefault(word, 0);
                frequency++;
                wordFrequencyMap.put(word, frequency);
                if (frequency > maxFrequency) {
                    mostCommonWord = word;
                    maxFrequency = frequency;
                }
            }
            return mostCommonWord;
        }
    }
    
    ############
    
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    class Solution {
        private static Pattern pattern = Pattern.compile("[a-z]+");
    
        public String mostCommonWord(String paragraph, String[] banned) {
            Set<String> bannedWords = new HashSet<>();
            for (String word : banned) {
                bannedWords.add(word);
            }
            Map<String, Integer> counter = new HashMap<>();
            Matcher matcher = pattern.matcher(paragraph.toLowerCase());
            while (matcher.find()) {
                String word = matcher.group();
                if (bannedWords.contains(word)) {
                    continue;
                }
                counter.put(word, counter.getOrDefault(word, 0) + 1);
            }
            int max = Integer.MIN_VALUE;
            String ans = null;
            for (Map.Entry<String, Integer> entry : counter.entrySet()) {
                if (entry.getValue() > max) {
                    max = entry.getValue();
                    ans = entry.getKey();
                }
            }
            return ans;
        }
    }
    
  • // OJ: https://leetcode.com/problems/most-common-word/
    // Time: O(N) where N is character count in paragraph
    // Space: O((B + P)W)
    //     where B is the size of ban list,
    //     P is unique count of words in paragraph that are not banned,
    //     and W is average word length
    class Solution {
    private:
        string getWord(string::iterator& it, string::iterator end) {
            while (it != end && !isalpha(*it)) ++it;
            string res;
            for (; it != end && isalpha(*it); ++it) {
                res += tolower(*it);
            }
            return res;
        }
    public:
        string mostCommonWord(string paragraph, vector<string>& banned) {
            unordered_map<string, int> m;
            unordered_set<string> ban(banned.begin(), banned.end());
            string word;
            string res;
            int maxCnt = 0;
            auto it = paragraph.begin();
            while ((word = getWord(it, paragraph.end())) != "") {
                if (ban.find(word) != ban.end()) continue;
                m[word]++;
                if (m[word] > maxCnt) {
                    maxCnt = m[word];
                    res = word;
                }
            }
            return res;
        }
    };
    
  • class Solution:
        def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
            s = set(banned)
            p = Counter(re.findall('[a-z]+', paragraph.lower()))
            return next(word for word, _ in p.most_common() if word not in s)
    
    ############
    
    class Solution:
        def mostCommonWord(self, paragraph, banned):
            """
            :type paragraph: str
            :type banned: List[str]
            :rtype: str
            """
            p = re.compile(r"[!?',;.]")
            sub_para = p.sub(' ', paragraph.lower())
            words = sub_para.split(' ')
            words = [word for word in words if word and word not in banned]
            count = collections.Counter(words)
            return count.most_common(1)[0][0]
    
  • func mostCommonWord(paragraph string, banned []string) string {
    	s := make(map[string]bool)
    	for _, w := range banned {
    		s[w] = true
    	}
    	counter := make(map[string]int)
    	var ans string
    	for i, mx, n := 0, 0, len(paragraph); i < n; {
    		if !unicode.IsLetter(rune(paragraph[i])) {
    			i++
    			continue
    		}
    		j := i
    		var word []byte
    		for j < n && unicode.IsLetter(rune(paragraph[j])) {
    			word = append(word, byte(unicode.ToLower(rune(paragraph[j]))))
    			j++
    		}
    		i = j + 1
    		t := string(word)
    		if s[t] {
    			continue
    		}
    		counter[t]++
    		if counter[t] > mx {
    			ans = t
    			mx = counter[t]
    		}
    	}
    	return ans
    }
    
  • function mostCommonWord(paragraph: string, banned: string[]): string {
        const s = paragraph.toLocaleLowerCase();
        const map = new Map<string, number>();
        const set = new Set<string>(banned);
        for (const word of s.split(/[^A-z]/)) {
            if (word === '' || set.has(word)) {
                continue;
            }
            map.set(word, (map.get(word) ?? 0) + 1);
        }
        return [...map.entries()].reduce(
            (r, v) => (v[1] > r[1] ? v : r),
            ['', 0],
        )[0];
    }
    
    
  • use std::collections::{HashMap, HashSet};
    impl Solution {
        pub fn most_common_word(mut paragraph: String, banned: Vec<String>) -> String {
            paragraph.make_ascii_lowercase();
            let banned: HashSet<&str> = banned.iter().map(String::as_str).collect();
            let mut map = HashMap::new();
            for word in paragraph.split(|c| !matches!(c, 'a'..='z')) {
                if word.is_empty() || banned.contains(word) {
                    continue;
                }
                let val = map.get(&word).unwrap_or(&0) + 1;
                map.insert(word, val);
            }
            map.into_iter()
                .max_by_key(|&(_, v)| v)
                .unwrap()
                .0
                .to_string()
        }
    }
    
    

All Problems

All Solutions