Published:
Updated:


Solution

from collections import defaultdict
from typing import List


class Solution:
    # ๊ฐ€์žฅ ๋งŽ์€ ๋‹จ์–ด๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ๋ฌธ์ œ
    # ๋Œ€์‹  banned์— ํฌํ•จ๋˜์–ด ์žˆ๋Š” ๋‹จ์–ด๋“ค์€ ์ œ์™ธํ•จ
    def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
        count_dic = defaultdict(int)
        split_paragraph = paragraph.replace('!', ' ').replace('?', ' ').replace("'", ' ').replace(',', ' ').replace(
            ';', ' ').replace(".", ' ').lower().split()

        # ๋งต ๋งŒ๋“ค๊ธฐ
        for s in split_paragraph:
            count_dic[s] += 1

        while True:
            max_key = max(count_dic, key=count_dic.get)

            # ๊ธˆ์ง€ ๋‹จ์–ด๊ฐ€ ํฌํ•จ์ด ์•ˆ ๋˜์–ด ์žˆ์œผ๋ฉด -> ๊ทธ๋ƒฅ ๋ฆฌํ„ด
            if max_key not in banned:
                return max_key

            # ๊ธˆ์ง€ ๋‹จ์–ด์— ํฌํ•จ๋ผ ์žˆ์œผ๋จผ -> ๋‹ค์‹œ while๋ฌธ ๋Œ๋ฉด์„œ ๋”•์…”๋„ˆ๋ฆฌ ์ œ๊ฑฐ
            count_dic.pop(max_key)


print(Solution().mostCommonWord("Bob hit a ball, the hit BALL flew far after it was hit.", ["hit"]))


Another Solution

  • r์€ raw string์„ ์˜๋ฏธํ•ฉ๋‹ˆ๋‹ค. ์ด๋Š” ๋ฌธ์ž์—ด์—์„œ ๋ฐฑ์Šฌ๋ž˜์‹œ๋ฅผ ์ผ๋ฐ˜ ๋ฌธ์ž๋กœ ์ฒ˜๋ฆฌํ•˜๋„๋ก ์ง€์‹œํ•˜๋Š”๋ฐ ์‚ฌ์šฉ๋ฉ๋‹ˆ๋‹ค.
  • ์˜ˆ๋ฅผ ๋“ค์–ด, \\ ๋Œ€์‹  \๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ด ๊ฒฝ์šฐ r'[^\w]'๋Š” [^\w]์™€ ๋™์ผํ•ฉ๋‹ˆ๋‹ค.
class Solution:
    def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
        words = [word for word re.sub(r'[^\w]', ' ', paragraph)
            .lower().split() if word not in banned]
        counts = collections.Counter(words)

        # (1): ๊ฐ€์žฅ ์ฒซ๋ฒˆ์งธ max๊ฐ’ -> [0]: ์ฒซ๋ฒˆ์งธ ํŠœํ”Œ -> [0]: ์ฒซ๋ฒˆ์งธ ์›์†Œ
        return counts.most_common(1)[0][0]

Leave a comment