LeetCode 819. Most Common Word
考点 | 难度 |
---|---|
Hash Table | Easy |
题目
Given a string paragraph
and a string array of the banned words banned
, return the most frequent word that is not banned. It is guaranteed there is at least one word that is not banned, and that the answer is unique.
The words in paragraph
are case-insensitive and the answer should be returned in lowercase.
思路
先去掉所有banned word,再统计每一个词的出现次数。
用空格分开string:paragraph.split("\\s+")
答案
public String mostCommonWord(String paragraph, String[] banned) {
Set<String> bannedWords = new HashSet<String>(Arrays.asList(banned));
paragraph = paragraph.toLowerCase();
String punctuation = "!?',;.";
for (char c : punctuation.toCharArray()) {
paragraph = paragraph.replace(c, ' ');
}
String[] tokens = paragraph.split("\\s+");
Map<String, Integer> frequencyTable = new HashMap<>();
for (String s: tokens) {
if (!bannedWords.contains(s)) {
frequencyTable.merge(s, 1, Integer::sum);
}
}
int maxFrequency = 0;
String maxWord = "";
for (Map.Entry<String, Integer> e : frequencyTable.entrySet()) {
if (e.getValue() > maxFrequency) {
maxFrequency = e.getValue();
maxWord = e.getKey();
}
}
return maxWord;
}