반응형
문제 링크 : leetcode.com/problems/most-common-word/submissions/
paragraph 중에 banned와 특수문자를 뺀 단어 중에 가장 빈도가 많은 단어를 찾는 것이 목표다. 결국에 책을 보고 풀었는데 문제에서 함정? 이라고 할 수 있는 것이 str
과 list
의 단어 제거 문제이다.
str.replace()
를 사용하면 banned 문자가 "abc"일 때 abcd는 d가 남게된다.
그렇다고 split()
으로 list를 만든 후 list.remove()
를 하면 한 개만 지워진다.
찾아보니 filter를 이용해서 지울 수는 있겠지만 banned loop를 돌아야해서 비효율적이다.
class Solution:
# 틀린 답안. str, list의 제한된 remove가 발목을 잡는다.
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
result = paragraph.lower()
for ban in banned:
result = result.replace(ban, "")
result = re.sub("[^0-9a-z ]", " ", result)
result_list = result.split()
answer = collections.Counter(result_list).most_common(1)
return answer[0][0]
아예 새로운 list를 만든다 생각하고 paragraph에서 단어만 뽑아서 넣는다. regex중 \w
를 쓰면 단어만 뽑히니 이것을 이용한다.
class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
result = [
word
for word in re.sub("[^\w]", " ", paragraph).lower().split()
if word not in banned
]
answer = collections.Counter(result).most_common(1)
return answer[0][0]
문자열 문제는 거의 대부분이 regex로 str에서 불필요한 것을 날리던가 아니면 새로운 리스트를 만들되 regex로 필요한 것만 뽑아서 만들던가 해야하는 것 같다.