-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLt819.java
More file actions
36 lines (29 loc) · 1.08 KB
/
Lt819.java
File metadata and controls
36 lines (29 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package string;
import java.util.*;
class Lt819 {
public String mostCommonWord(String paragraph, String[] banned) {
Set<String> bans = new HashSet<>(Arrays.asList(banned));
// replaceAll() -> 특수문자 변환.
// 소문자 변환, 공백 기준 분리
String[] words = paragraph.replaceAll("\\W+", " ").toLowerCase().split(" ");
// 단어 개수 저장
Map<String, Integer> counts = new HashMap<>();
// 단어 빈도수 계산
for (String word : words) {
if (!bans.contains(word)) {
counts.put(word, counts.getOrDefault(word, 0) + 1);
}
}
// 가장 많이 나온 단어 찾기
// counts 엔트리셋으로 가져와서 비교 후 key값 리턴
String mostCommon = "";
int maxCount = 0;
for (Map.Entry<String, Integer> entry : counts.entrySet()) {
if (entry.getValue() > maxCount) {
mostCommon = entry.getKey();
maxCount = entry.getValue();
}
}
return mostCommon;
}
}