ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 819. Most Common Word
    Programming/leetcode 2021. 1. 21. 12:40
    728x90
    • 문단과 금지어가 주어지는데, 가장 많이 나온 단어를 출력
    • 단, 금지어에 포함안되어 있어야함\
    • 사용되는 특수문자는 문제에서 주어진다.
    • 정규식을 사용하면 문단을 구분하기 쉬움
    • 리스트 컴프리헨션을 이용해서 새로운 리스트 만들어보기
    • most_common()을 자주 사용할 것 같음
    def mostCommonWord(paragraph, banned) -> str:
        # 리스트 컴프리헨션을 이용해서 새로운 리스트를 만든다.
        # 정규 표현식으로 현재 paragraph에서 특수문자를 공백으로 만들고, 공백 기준으로 문자를 잘라서 넣어둔다.
        change_sub = [word for word in re.sub('[.,!?\';]', ' ', paragraph.lower()).split()]
        
        # 책에 나온 방법인데, 나눈 문자열이 banned에 있는지 한번 확인하고 넣어주도록 하는것
        # 이게 더 깔끔하다. 밑에 for문 한번 더 안써도 되고
        change_sub2 = [word for word in re.sub('[/W]', ' ', paragraph).lower().split() if word not in banned]
    
        counter = collections.Counter(change_sub)
        result_count = counter.most_common()
        for item in result_count:
            if item[0] in banned:
                continue
            else:
                return item[0]
        return ""
    

    'Programming > leetcode' 카테고리의 다른 글

    1437. Check If All 1's Are at Least Length K Places Away  (0) 2021.01.26
    5. Longest Palindromic Substring  (0) 2021.01.25
    49. Group Anagrams  (0) 2021.01.21
    937. Reorder Data in Log Files  (0) 2021.01.21
    125. Valid Palindrome  (0) 2021.01.21
Designed by Tistory.