Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 데이터드리븐
- 스타터스부트캠프
- python
- 정렬
- Til
- ndarray
- 유데미
- matplotlb
- 유데미코리아
- 시각화
- 부트캠프후기
- 취업부트캠프
- numpy
- pandas
- 유데미큐레이션
- 데이터시각화
- 데이터프레임
- 브루트포스 알고리즘
- 판다스
- 유데미부트캠프
- Leetcode
- 태블로
- DataFrame
- 그리디 알고리즘
- 백준
- 코딩테스트
- 데이터분석
- Tableau
- 파이썬
- 넘파이
Archives
- Today
- Total
Diary, Data, IT
[LeetCode] 819. Most Common Word - Python 본문
[LeetCode] 819. Most Common Word - Python
Most Common Word - LeetCode
Can you solve this real interview question? Most Common Word - Given a string paragraph and a string array of the banned words banned, return the most frequent word that is not banned. It is guaranteed there is at least one word that is not banned, and tha
leetcode.com
문제
특정 문단과 금지 단어의 배열이 주어지며, 금지되지 않은 가장 많이 등장한 단어를 반환하는 문제입니다.
문단의 단어는 대소문자를 구분하지 않으며, 답은 소문자로 반환되어야 합니다.
아이디어
리스트에 포함된 요소의 수를 세는 collections.Counter를 이용하면 문제를 쉽게 해결할 수 있다.
하지만 단어를 세기 전에 미리 불필요한 특수문자는 제거하고, 소문자로 변환해주는 등의 전처리가 필요하다.
또 단어를 센 결과에 금지된 단어(banned)가 포함되어 있다면 이는 제외하고, most_common 단어를 반환한다.
코드
class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
import collections
import re
# 대소문자 구분을 하지 않고, 특수문자 무시
paragraph2 = paragraph.lower()
paragraph2 = re.sub('[^a-z0-9]', ' ', paragraph2)
word = paragraph2.split(' ')
result = collections.Counter(word)
banned.append('') #공백도 count에서 제거
for ban in banned:
if ban in result:
del result[ban]
return result.most_common(1)[0][0]
'Coding Test > LeetCode' 카테고리의 다른 글
[LeetCode] 200. Number of Islands - Python (0) | 2023.04.15 |
---|---|
[LeetCode] 3. Longest Substring Without Repeating Characters - Python (0) | 2023.04.14 |
[LeetCode] 937. Reorder Data in Log Files - Python (0) | 2023.04.11 |
[LeetCode] 344. Reverse String - Python (0) | 2023.04.11 |
[LeetCode] 125. Valid Palindrome - Python (0) | 2023.04.10 |