-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMostCommonWord.java
More file actions
34 lines (30 loc) · 1.06 KB
/
Copy pathMostCommonWord.java
File metadata and controls
34 lines (30 loc) · 1.06 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
class Solution {
// Time: O(P+B),where P is the size of paragraph and B is the size of banned.
// Space: O(P+B), to store the count and the banned set.
public String mostCommonWord(String paragraph, String[] banned) {
// split paragraph
String[] words = paragraph.toLowerCase().split("\\W+");
// add banned words to set
Set<String> set = new HashSet<>();
for(String word : banned){
set.add(word);
}
// add paragraph words to hash map
Map<String, Integer> map = new HashMap<>();
for(String word : words){
if(!set.contains(word)){
map.put(word, map.getOrDefault(word, 0) + 1);
}
}
// get the most frequent word
int max = 0; // max frequency
String res = "";
for(String str : map.keySet()){
if(map.get(str) > max){
max = map.get(str);
res = str;
}
}
return res;
}
}