Most Common Word

Posted by chunyang on April 7, 2019


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.



paragraph = “Bob hit a ball, the hit BALL flew far after it was hit.”

banned = [“hit”]

Output: “ball”


  • “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.


  • 1 <= paragraph.length <= 1000.
  • 0 <= 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.


这题其实难度不是很大,主要是这题如果想尽量使用 STL 的算法,还是有几个点可以学习。

vector 初始化 set

vector<int> a{1,2,3};
set<int> b(a.begin(), a.end());
set<init> c;
copy(a.begin(), a.end(), inserter(c, c.end()));

inserter 有 3 种:

  • back_inserter(container)
  • front_inserter(container)
  • inserter(container, pos)


string a = "I am NOT happy";
transform(a.begin(), a.end(), a.begin(), ::tolower);

python Counter, defaultdict, re

defaultdict 是有默认值的字典,这在很多解法中很有用,C++ 的字典当调用 [key] 去访问时会自动增加 默认值,Python 不会。它的构造函数要求是 callable

from collections import defaultdict

d = defaultdict(int)
e = defaultdict(lambda:return 3)

Counter 是做统计用的,

  • 如果它的构造函数是一个字符串,它会统计每个字符出现的次数
  • 如果它的构造函数是一个 dict,包括 kwargs 这种形式,它会利用字典 key 和 value 构造 Counter
  • most_common([n]): 返回频率最高的 n 个,n 不提供时,返回所有

re.split 是按照正则匹配去切分字符串,str.split 是按照指定的字符去切分

import re
a = "i,love:you"
b = a.split(",:")
c = re.split("[,:]", a)




class Solution {
    string mostCommonWord(string paragraph, vector<string>& banned) {
        int i = 0;
        int j = 0;
        int length = paragraph.size();
        transform(paragraph.begin(), paragraph.end(), paragraph.begin(), ::tolower);
        set<string> ba(banned.begin(), banned.end());
        int max_len = -1;
        string max_word = "";
        map<string, int> counter;
        while (i < length) {
            /* skip leading bad words */
            while (i < length && (paragraph[i]>'z' || paragraph[i]<'a')) i++;
            if (i == length) break;
            j = i;
            /* found bound for current word */
            while (j < length && (paragraph[j]<='z' && paragraph[j]>='a')) j++;

            /* substr current word */
            string s = paragraph.substr(i, j - i);
            counter[s] += 1;
            if (ba.find(s) == ba.end() && counter[s] > max_len) {
                max_word = s;
                max_len = counter[s];
            i = j;
        return max_word;
class Solution(object):
    def mostCommonWord(self, paragraph, banned):
        :type paragraph: str
        :type banned: List[str]
        :rtype: str
        import re
        from collections import defaultdict
        from collections import Counter
        paragraph = paragraph.lower()
        banned = set(banned)
        words = re.split("[!?',;. ]", paragraph)
        words = filter(lambda x:len(x)!=0 and x not in banned, words)
        d = defaultdict(int)
        for word in words:
            d[word] += 1
        c = Counter(d)
        return c.most_common(1)[0][0]


Creative Commons License
This work is licensed under a CC A-S 4.0 International License.