题目
Given a paragraph and a list of banned words, return the most frequent word that is not in the list of banned words. It is guaranteed there is at least one word that isn't banned, and that the answer is unique.
Words in the list of banned words are given in lowercase, and free of punctuation. Words in the paragraph are not case sensitive. The answer is in lowercase.
答案
class Solution {
public String mostCommonWord(String paragraph, String[] banned) {
Set<String> banned_set = new HashSet<String>();
Map<String, Integer> map = new HashMap<String, Integer>();
String ans = "";
int ansfreq = 0;
String paragraph2 = "";
// Remove punctuations
for(int i = 0; i < paragraph.length(); i++) {
char c = paragraph.charAt(i);
if(c != '.' && c != ',' && c != '!' && c != ':' && c != '(' && c != ')' && c != '?' && c != ';' && c != '\'')
paragraph2 = paragraph2 + c;
}
for(String s : banned) {
banned_set.add(s);
}
// Split paragraph into words, remove all banned words
String[] words = paragraph2.split(" ");
for(String word : words) {
String word_lower = word.toLowerCase();
if(banned_set.contains(word_lower)) continue;
Integer freq = (map.get(word_lower) == null)?0:map.get(word_lower);
map.put(word_lower, freq + 1);
if(freq + 1 > ansfreq) {
ans = word_lower;
ansfreq = freq + 1;
}
}
return ans;
}
}