[Leetcode]819. Most Common Word
📄 Description
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 that the answer is unique.
The words in paragraph
are case-insensitive and the answer should be returned in lowercase.
Example 1:
Input: paragraph = "Bob hit a ball, the hit BALL flew far after it was hit.", banned = ["hit"]
Output: "ball"
Explanation:
"hit" occurs 3 times, but it is a banned word.
"ball" occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph.
Note that words in the paragraph are not case sensitive,
that punctuation is ignored (even if adjacent to words, such as "ball,"),
and that "hit" isn't the answer even though it occurs more because it is banned.
Example 2:
Input: paragraph = "a.", banned = []
Output: "a"
Constraints:
1 <= paragraph.length <= 1000
- paragraph consists of English letters, space
' '
, or one of the symbols:"!?',;."
. 0 <= banned.length <= 100
1 <= banned[i].length <= 10
banned[i]
consists of only lowercase English letters.
💻 My submission
class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
words=[x for x in re.sub('[^\w]', ' ', paragraph).lower().split() if x not in banned]
counter=Counter(words)
return counter.most_common(1)[0][0]
🔨 How to solve the problm
1. 정규식을 사용하여 입력값에 대한 전처리 진행
- 단어 문자가 아닌 모든 문자를 공백으로 치환한다.
2. Counter
객체 활용하여 most_common(1)
로 답 구하기
References
- https://leetcode.com/problems/most-common-word/
- 파이썬 알고리즘 인터뷰(95가지 알고리즘 문제 풀이로 완성하는 코딩 테스트), 박상길 지음
Author And Source
이 문제에 관하여([Leetcode]819. Most Common Word), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@limelimejiwon/Leetcode819.-Most-Common-Word저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)