문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음
문자열 paragraph와 금지된 단어들이 있는 문자열 배열 banned가 주어졌을 때, 금지되지 않은 단어 중 가장 자주 사용되는 단어를 반환해라. 금지되지 않은 단어가 최소 하나 이상 포함되어 있으며, 정답은 고유한 것을 보장한다.
paragraph에 단어들은 대소문자를 구분하지 않고, 정답은 소문자로 반환해야 한다.
#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"
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();
}
}