문제 해석:
문장이 주어진다. 문장은 대소문자, 여러 기호들이 들어간다.
banned 리스트에는 답에서 걸러낼 단어들이 들어있다.
banned 에 들어있지 않는 단어들중에 가장 많이 언급된 단어를 구해라.
문제 해설:
1. 문장리스트를 한글자씩 받는다.
2. 알파벳이면 소문자로 다 변환해준다.
3. 다른 기호거나 띄어쓰기는 모두 띄어쓰기로 넣는다.
4. 띄어쓰기를 기준으로 split한다.
5. banned에 있는 단어가 아니면 딕셔너리에 넣고 개수를 올려준다.
6. 딕셔너리에 저장된 개수를 이용하여 최대값을 구한다.
819. 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 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.
소스코드:
import re
class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
nstr = ''
for c in paragraph:
if c.isalnum():
nstr += c.lower()
else:
nstr += ' '
words = nstr.split()
worCnt = dict()
for word in words:
if word not in banned:
if word in worCnt:
worCnt[word] += 1
else:
worCnt[word] = 1
maxV = 0
ans = ''
for key, val in worCnt.items():
if val > maxV:
maxV = val
ans = key
return ans
'컴퓨터공학 > LeetCode 1000' 카테고리의 다른 글
[LeedCode] 929. Unique Email Addresses 파이썬 (Easy) (0) | 2021.12.21 |
---|---|
[LeedCode] 1167. Minimum Cost to Connect Sticks 파이썬 Medium (0) | 2021.11.06 |
[LeedCode] 53. Maximum Subarray 파이썬 Easy (0) | 2021.11.04 |
[LeedCode] 175. Combine Two Tables SQL Easy (0) | 2021.11.03 |
[LeedCode] 423. Reconstruct Original Digits from English 파이썬 Medium (0) | 2021.11.03 |