-
Notifications
You must be signed in to change notification settings - Fork 0
/
MostCommonWord.java
44 lines (39 loc) · 1.26 KB
/
MostCommonWord.java
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
44
package string;
import utils.LeetCode;
import utils.Level;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
@LeetCode(no=819,title = "Most Common Word",url = "https://leetcode.com/problems/most-common-word/",level = Level.EASY)
public class MostCommonWord {
public String mostCommonWord(String paragraph, String[] banned) {
Set<String> bannedSet=new HashSet<>();
for(String b:banned){
bannedSet.add(b);
}
paragraph = paragraph.toLowerCase();
paragraph = paragraph.replaceAll("\\W"," ");
// System.out.println(paragraph.replaceAll(","," ").replaceAll("[^a-zA-Z\\s]",""));
String paragraphArray[]=paragraph.split("\\s+");
Map<String,Integer> map=new HashMap<>();
String current="";
for(String s: paragraphArray){
current=s.toLowerCase().trim();
if(! bannedSet.contains(current)){
// System.out.println(current);
map.compute(current,(k,v)->(v==null)?1:v+1);
}
}
Set<String>keys= map.keySet();
String mostFreq="";
int mostFreqCount=0;
for(String s:keys){
if(map.get(s)>mostFreqCount){
mostFreqCount=map.get(s);
mostFreq=s;
}
}
return mostFreq;
}
}