[LeetCode] 819. Most Common Word

원숭2·2022년 2월 5일
0

LeetCode

목록 보기
32/51

문제

풀이

  1. 계산의 편의성을 위해 lower함수로 문자를 소문자로 바꿔 주고 이를 list로 변환함.
  2. for문을 돌며 소문자가 아닌 문자들은 전부 공백으로 바꿔 줌.
  3. join함수를 통해 list에서 문자열로 바꿔준 후 split함수를 사용해 공백을 기준으로 split함.
  4. count란 dictionary를 만들어 단어의 갯수를 세어줌.
    1) count에 존재하지 않고 banned에 속하지 않은 단어인 경우 count에 추가함.
    2) count에 존재하는 단어인 경우 기존 값에 +1 해줌.
  5. 최빈값을 구하기 위해 items 함수를 사용하여 (key, value)형태로 return 받은 후, 이를 lambda식과 sort함수를 사용하여 빈도의 내림차순으로 정렬해주고, 결과값 return함.

코드

class Solution:
    def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
        paragraph = list(paragraph.lower())
        for i in range(len(paragraph)) :
            if ord(paragraph[i]) not in range(97, 123) :
                paragraph[i] = ' '
        paragraph = ''.join(paragraph).split()
        
        count = dict()
        for p in paragraph :
            if p not in count.keys() :
                if p in banned :
                    continue
                else :
                    count[p] = 1
            else :
                count[p] += 1
        res = sorted(list(count.items()), key = lambda x : -x[1])
        
        return res[0][0]

0개의 댓글