[LeetCode] Most Common Word

아르당·2026년 2월 28일

LeetCode

목록 보기
175/213
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

문자열 paragraph와 금지된 단어들이 있는 문자열 배열 banned가 주어졌을 때, 금지되지 않은 단어 중 가장 자주 사용되는 단어를 반환해라. 금지되지 않은 단어가 최소 하나 이상 포함되어 있으며, 정답은 고유한 것을 보장한다.

paragraph에 단어들은 대소문자를 구분하지 않고, 정답은 소문자로 반환해야 한다.

Example

#1
Input: paragraph = "Bob hit a ball, the hit BALL flew far after it was hit.", banned = ["hit"]
Output: "ball"
Explanation: "hit"은 세 번 나오지만 금지어이다.
"ball"은 두 번 나오고, 문단에서 금지어가 아닌 단어 중 가장 자주 나온다.

#2
Input: paragraph = "a.", banned = []
Output: "a"

Constraints

  • 1 <= paragraph.length <= 1000
  • paragraph는 영문자, 공백 ' ', 기호("!?',;.") 중 하나로 구성된다.
  • 0 <= banned.length <= 100
  • 1 <= banned[i].length <= 10
  • banned[i]는 영어 소문자로만 구성된다.

Solved

class Solution {
    public String mostCommonWord(String paragraph, String[] banned) {
        Set<String> ban = new HashSet<>(Arrays.asList(banned));
        Map<String, Integer> count = new HashMap<>();
        String[] words = paragraph.replaceAll("\\W+", " ").toLowerCase().split("\\s+");

        for(String word : words){
            if(!ban.contains(word)){
                count.put(word, count.getOrDefault(word, 0) + 1);
            }
        }

        return Collections.max(count.entrySet(), Map.Entry.comparingByValue()).getKey();
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글