[Leetcode] 819. Most Common Word

bradley·2022년 6월 8일
2

Algorithm

목록 보기
8/12

Problem

Solution

1) 리스트 컴프리헨션, defaultdict() 사용

개수를 담아두는 변수는 딕셔너리를 사용하며 defaultdict()를 사용해 int 기본값이 자동으로 부여되게 했다. 따라서 여기서는 키 존재 유무를 확인할 필요없이 즉시 counts[word] += 1 을 수행할 수 있다.

class Solution:
    def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
				# re.sub()로 쉼표 등 구두점 데이터 클렌징
				# 공백을 기준으로 단어 요소를 갖는 리스트 생성
        words = [word for word in re.sub(r'[^\w]', ' ', paragraph).lower().split() if word not in banned]
        counts = collections.defaultdict(int)
		for word in words:
			counts[word] += 1
        
	return max(counts, key=counts.gets)

정규식

\w : 단어 문자(Word Character)

^ : not

2) 리스트 컴프리헨션, Counter 객체 사용

개수 처리 부분을 Counter 모듈을 사용해 좀 더 깔끔하게 처리

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]
        counts = collections.Counter(words)
        
        # 가장 흔하게 등장하는 단어의 첫 번째 index return
        """
        ex) 
        most_common(1) : [('ball', 2)]
        most_common(1)[0][0] : ball ← 첫 번째 index의 key 추출
        """
	return counts.most_common(1)[0][0]
profile
데이터 엔지니어링에 관심이 많은 홀로 삽질하는 느림보

0개의 댓글