2025-08-01 04:33:33 +0000 UTC

Most Common Word

Code

class Solution:
    def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
        freqs = defaultdict(int)
        banned_set = set(banned)
        cur_word = []
        for char in itertools.chain(paragraph, "."):
            if char.isalpha():
                cur_word.append(char.lower())
                continue
            if not cur_word:
                continue
            word = "".join(cur_word)
            if word not in banned_set:
                freqs[word] += 1
            cur_word.clear()
        most_freq = ""
        most_freq_freq = 0
        for word, freq in freqs.items():
            if freq > most_freq_freq:
                most_freq, most_freq_freq = word, freq
        return most_freq