LeetCode 819. 【Java】819. Most Common Word
原题链接
简单
作者:
tt2767
,
2020-03-26 17:03:19
,
所有人可见
,
阅读 839
/**
1. 先把段落中的单词划分出来并转换为小写
2. 统计所有单词的频率
3. 把ban-list中单词频率置为-1
4. 遍历所有单词, 输出频率最高的
*/
class Solution {
public String mostCommonWord(String paragraph, String[] banned) {
Map<String, Integer> freq = new TreeMap<>();
List<String> slice = wordBreak(paragraph);
for (int i = 0; i < slice.size() ; i ++){
String word = slice.get(i);
if (freq.get(word) == null) freq.put(word, 0);
freq.put(word, freq.get(word) + 1);
}
for (int i = 0; i < banned.length; i++){
freq.remove(banned[i]);
}
int maxFreq = 0;
String res = null;
for (String word : freq.keySet()){
if (freq.get(word) > maxFreq){
res = word;
maxFreq = freq.get(word);
}
}
return res;
}
public List<String> wordBreak(String paragraph){
List<String> slices = new ArrayList<>();
StringBuilder buffer = new StringBuilder();
for (int i = 0 ; i < paragraph.length(); i++){
char c = paragraph.charAt(i);
if ('a' <= c && c <= 'z' || 'A' <= c && c <= 'Z'){
buffer.append(c);
} else if (buffer.length() != 0){
slices.add(buffer.toString().toLowerCase());
buffer.setLength(0);
}
}
if (buffer.length() != 0) slices.add(buffer.toString().toLowerCase());
return slices;
}
}