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
37
38
39
40
41
42
43
| class Solution {
public String mostCommonWord(String paragraph, String[] banned) {
Set<String> bannedSet = new HashSet<String>();
for(String ban: banned) {
bannedSet.add(ban);
}
StringBuffer sb = new StringBuffer();
Map<String, Integer> dataMap = new HashMap<String, Integer>();
String max = "";
for(char ch : paragraph.toCharArray()) {
if(ch == ' ' || ch == ',') {
if(sb.length() > 0) {
max = addWordToMap(sb, bannedSet, dataMap, max);
sb.setLength(0);
}
}
else {
if(Character.isAlphabetic(ch)) {
sb.append(ch);
}
}
}
if(sb.length() > 0) {
max = addWordToMap(sb, bannedSet, dataMap, max);
}
return max;
}
public String addWordToMap(StringBuffer sb, Set<String> bannedSet, Map<String, Integer> dataMap, String max) {
String word = sb.toString().toLowerCase();
if(bannedSet.contains(word))
return max;
dataMap.put(word, dataMap.getOrDefault(word, 0) + 1);
if(dataMap.get(word) > dataMap.getOrDefault(max, 0)) {
return word;
}
return max;
}
}
|