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
- 위상 정렬(Topological Sort)
- 플로이드 워셜 알고리즘(Floyd-Warshall Algorithm)
- DFS & BFS
- 다익스트라 알고리즘(Dijkstra Algorithm)
- 이분 탐색(Binary Search)
- 백준 2493번
- 스택(Stack)
- BFS(Breadth First Search)
- 동적 프로그래밍(Dynamic Programming)
- DFS
- 백준 17608번
- 트리(Tree)
- 위상 정렬(Topology Sort)
- DFS(Depth First Search)
- 그래프(Graph)
- 백준 18352번
- 분할 정복(Divide and Conquer)
- BFS
- 이분 그래프(Bipartite Graph)
- 백준 10000번
- 백준 2261번
- 백준 1707번
- 알고리즘 개념
- 그리디 알고리즘(Greedy Algorithm)
- 큐(Queue)
- 백준 2812번
- 백준 21606번
- 백준 2504번
- 백준 9012번
- 백준 1948번
Archives
- Today
- Total
Always Be Wise
문자열 조작 : 가장 흔한 단어(리트코드 819번) 본문
728x90
▶ 문제 : https://leetcode.com/problems/most-common-word/
Most Common Word - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
##### 문제 #####
금지된 단어를 제외한 가장 흔하게 등장하는 단어를 출력하라.
대소문자 구분을 하지 않으며, 구두점(마침표, 쉼표 등) 또한 무시한다.
##### 입력 #####
paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
banned = ["hit"]
##### 출력 #####
"ball"
▶ 접근 방법
리스트 컴프리헨션과 Counter 객체를 사용하여 해결하였다.
입력값에는 대소문자가 섞여 있으며 쉼표 등 구두점이 존재한다.
정규식을 사용하여 처리할 수 있다.
\w는 단어 문자(Word Character)를 의미하며, ^은 not을 의미한다.
따라서 re.sub(r'[^\w]', ' ', paragraph)의 의미는
단어 문자가 아닌 모든 문자를 공백으로 치환(Substitute)하는 역할을 한다.
▶ 풀이 코드
from typing import List
from collections import Counter
import re
paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
banned = ["hit"]
def most_common_word(string:str, banned: List[str]) -> str:
words = [word for word in re.sub(r'[^\w]', ' ', paragraph).lower().split() if word not in banned]
counts = Counter(words)
return counts.most_common(1)[0][0]
print(most_common_word(paragraph, banned))
▶ 관련 링크
2021.12.14 - [알고리즘/리트코드] - 문자열 조작 : 유효한 팰린드롬(리트코드 125번)
2021.12.14 - [알고리즘/리트코드] - 문자열 조작 : 문자열 뒤집기(리트코드 344번)
2021.12.14 - [알고리즘/리트코드] - 문자열 조작 : 로그 파일 재정렬(리트코드 937번)
'알고리즘 > 리트코드' 카테고리의 다른 글
문자열 조작 : 가장 긴 팰린드롬 부분 문자열(리트코드 5번) (0) | 2021.12.14 |
---|---|
문자열 조작 : 그룹 애너그램(리트코드 49번) (0) | 2021.12.14 |
문자열 조작 : 로그 파일 재정렬(리트코드 937번) (0) | 2021.12.14 |
문자열 조작 : 문자열 뒤집기(리트코드 344번) (0) | 2021.12.14 |
문자열 조작 : 유효한 팰린드롬(리트코드 125번) (0) | 2021.12.14 |
Comments