[LeetCode] 819. Most Common Word

2021. 1. 5. 12:10Problem Solving/LeetCode

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

 

Most Common Word - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

내 풀이

import collections
import re
from typing import OrderedDict


class Solution:
    def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
        word_dic = {}
        sorted_dic = {}
        tmp = re.sub(pattern='\W', repl=' ', string=paragraph).lower().split()

        for s in tmp:
            if s not in banned:
                if s in word_dic:
                    word_dic[s] += 1
                else:
                    word_dic[s] = 1

        # value기준으로 딕셔너리 정렬
        sorted_dic = OrderedDict(sorted(word_dic.items(),
                                        key=lambda x: x[1],
                                        reverse=True))
        for k in sorted_dic.keys():
            return k

Counter 이용한 책 풀이

https://github.com/onlybooks/algorithm-interview/blob/master/2-python/ch06/4-1.py

 

onlybooks/algorithm-interview

<파이썬 알고리즘 인터뷰> 95가지 알고리즘 문제 풀이로 완성하는 코딩 테스트. Contribute to onlybooks/algorithm-interview development by creating an account on GitHub.

github.com

더 알아보기

 

책 정보

파이썬 알고리즘 인터뷰
국내도서
저자 : 박상길
출판 : 책만 2020.07.15
상세보기
반응형