• 문제 링크
Most Common Word - LeetCode
Can you solve this real interview question? 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 tha
leetcode.com
• 풀이 코드
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Solution {
public String mostCommonWord(String paragraph, String[] banned) {
Matcher mat = Pattern.compile("[a-z]+").matcher(paragraph.toLowerCase());
Set<String> set = new HashSet<>(Arrays.asList(banned));
Map<String, Integer> map = new HashMap<>();
String res = "";
int max = 0;
while (mat.find()) {
String s = mat.group();
if (set.contains(s)) continue;
int cnt = map.getOrDefault(s, 0) + 1;
map.put(s, cnt);
if (max < cnt) {
max = cnt;
res = s;
}
}
return res;
}
}'Problem Solving > LeetCode' 카테고리의 다른 글
| [LeetCode] 824. Goat Latin - Java (0) | 2026.10.21 |
|---|---|
| [LeetCode] 821. Shortest Distance to a Character - Java (0) | 2026.10.20 |
| [LeetCode] 812. Largest Triangle Area - Java (0) | 2026.10.18 |
| [LeetCode] 806. Number of Lines To Write String - Java (0) | 2026.10.17 |
| [LeetCode] 804. Unique Morse Code Words - Java (0) | 2026.10.16 |
댓글