[Leet Code] 819. Most Common Word

Seo Seung Woo·2022년 7월 11일
0
post-thumbnail

819. Most Common Word


❔Thinking

  • 주어진 문자열을 조건에 맞게 변환하고, 각 단어의 빈도수를 알아낸다.
  • banned에 포함되지 않은 단어 가운데 최빈 단어를 반환한다.

💻Solution

class Solution:
    def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
        paragraph_adj = re.sub('[^ a-zA-Z]', ' ', paragraph.lower())
        words_list_count = dict(collections.Counter(paragraph_adj.split()))
        words_list_count = sorted(words_list_count.items(), key=lambda x: x[1], reverse=True)
        print(words_list_count)
        for word in words_list_count:
            if word[0] not in banned:
                return word[0]

🗝️keypoint

  • re.sub()을 사용하여, 알파벳이 아닌 다른 문자는 모두 제거해야 한다. 이때,
    비어있는 문자열 ''로 만들 경우 'a,b,c'가 'abc'로 바뀌기 때문에 ' '공백으로 바꾸어야 한다.
profile
Code for people

0개의 댓글