알고리즘/Problem Solving
[LeetCode] Most Common Word
도툐리
2021. 4. 12. 11:28
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
(0) 맨 처음에 내가 작성했던 코드
=> 디버깅하는데에 시간이 꽤 걸림 ㅠㅠ
< , . ! > 등이 같이 붙어있는 애들의 경우 (ex) hit. 를 어떻게 처리해줘야 할지에 대한 고민들이 있었음...
그리고 collections.Counter(str) 를 하는것만으로는 빈도 높은 순서대로 배열되지 않고,
반드시 collections.Counter(str).most_common()까지 해줘야 정렬된 딕셔너리가 반환된다는 것을 알게됨.
class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
# pre-processing
paragraph = re.sub(r"[^A-Za-z]+", ' ', paragraph)
paragraph_list = [v.lower() for v in paragraph.split()]
# use Counter from collections to count the frequency of each words
paragraph_counter = collections.Counter(paragraph_list)
for banned_word in banned:
del(paragraph_counter[banned_word])
return paragraph_counter.most_common()[0][0]
(1) <파이썬 알고리즘 인터뷰> : 리스트 컴프리헨션, Counter 객체 사용
(2) <파이썬 알고리즘 인터뷰> :
(3) <파이썬 알고리즘 인터뷰> :
내용 참고 및 출처 :
책 <파이썬 알고리즘 인터뷰>