Leetcode 837 Solution

This article provides solution to leetcode question 837 (most-common-word)

https://leetcode.com/problems/most-common-word

Solution

class Solution(object):
    def mostCommonWord(self, paragraph, banned):
        """
        :type paragraph: str
        :type banned: List[str]
        :rtype: str
        """
        words = re.split("!|\?|'|,|;|\.| ", paragraph)
        word_map = {}

        for word in words:
            word = word.lower()
            if not word:
                continue

            if word in banned:
                continue

            if word not in word_map:
                word_map[word] = 0

            word_map[word] += 1

        max_word = None
        max_word_cnt = 0

        for word, word_cnt in word_map.items():
            if max_word_cnt < word_cnt:
                max_word = word
                max_word_cnt = word_cnt

        return max_word