-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathMostCommonWord.java
More file actions
51 lines (48 loc) · 1.51 KB
/
MostCommonWord.java
File metadata and controls
51 lines (48 loc) · 1.51 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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package Leetcode;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* @author szh
* @create 2018-08-18 23:31
**/
public class MostCommonWord {
public static void main(String[] args) {
new MostCommonWord().mostCommonWord("Bob hit a ball, the hit BALL flew far after it was hit.", new String[]{"hit"});
}
public String mostCommonWord(String paragraph, String[] banned) {
String[] words = paragraph.split(" ");
Set<String> set = new HashSet<>();
for (String s : banned) {
set.add(s);
}
Map<String, Integer> map = new HashMap<>();
for (String word : words) {
StringBuffer sb = new StringBuffer();
char[] cArray = word.toCharArray();
for (char c : cArray) {
if (Character.isLetter(c)) {
sb.append(c);
}
}
// word= word.replace(",","");
// word= word.replace(".","");
word = sb.toString();
word = word.toLowerCase();
map.put(word, map.get(word) == null ? 1 : map.get(word) + 1);
}
for (String s : set) {
map.remove(s);
}
String max = null;
int maxNum = 0;
for (Map.Entry temp : map.entrySet()) {
if ((int) temp.getValue() > maxNum) {
maxNum = (int) temp.getValue();
max = (String) temp.getKey();
}
}
return max;
}
}