LeetCode 819. Most Common Word

개발공부를해보자·2025년 1월 5일

LeetCode

목록 보기
4/95

파이썬 알고리즘 인터뷰 문제 4번(리트코드 819번) Most Common Word
https://leetcode.com/problems/most-common-word/

나의 풀이1

class Solution:
    def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
        clean_text = re.sub("[^a-zA-Z\s]", " ", paragraph)
        clean_text = clean_text.lower()
        word_list = clean_text.split()
        count_dict = dict()

        for word in word_list:
            if word in count_dict:
                count_dict[word] += 1
            else:
                count_dict[word] = 0
        
        count_list = list(sorted(count_dict.items(), key=lambda item: -item[1]))

        for candi, freq in count_list:
            if candi not in banned:
                return candi

나의 풀이2

class Solution:
    def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
        cleaned = re.sub(r"[^a-z\s]", " ", paragraph.lower())
        for word in dict(sorted(collections.Counter(cleaned.split()).items(), key = lambda item: item[1], reverse = True)):
            if word not in banned:
                return word

다른 풀이

class Solution:
    def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
        words = [word for word in re.sub(r"[^\w]", " ", paragraph).lower().split() if word not in banned]
        return collections.Counter(words).most_common(1)[0][0]

오답

  • 테스트 케이스
    "a, a, a, a, b,b,b,c, c”
  • 틀린 코드
    re.sub(r"[^a-z\s]", "", paragraph.lower())
    b,b,b,cbbbc가 되어 단어 구분이 되지 않는다. 공백을 주어 단어 구분할 필요가 있다.
  • 수정 코드
    re.sub(r"[^a-z\s]", " ", paragraph.lower())

배운 점, 익숙해져야할 표현

collections.Counter() , s붙는 것이랑 대문자 C 유의
collections.Counter().most_common(1)[0][0]
dict.items()
re.sub(r”[^\w]”, “ “, praragraph)

collections.Counter()에 대한 글
https://velog.io/@coding_study/collections.Count와-PEP-8

profile
개발 공부하는 30대 비전공자 직장인

0개의 댓글