class Solution {
public String mostCommonWord(String paragraph, String[] banned) {
HashSet<String> set=new HashSet<>();
for(String s:banned){
set.add(s);
}
String[] words=transfer(paragraph);
HashMap<String,Integer> map=new HashMap<>();//单词出现次数
int max=0;
String res="";
for(String word:words){
if(set.contains(word)){//不能在禁用列表中
continue;
}
map.put(word,map.getOrDefault(word,0)+1);
int count=map.get(word);
if(count>max){
max=count;
res=word;
}
}
return res;
}
public String[] transfer(String s){
//还要不区分大小写。
ArrayList<String> list=new ArrayList<>();
StringBuilder tmp=new StringBuilder();
for(int i=0;i<s.length();i++){
char c=s.charAt(i);
if(c>='a'&&c<='z'){
tmp.append(c);
}
else if(c>='A'&&c<='Z'){
tmp.append(Character.toLowerCase(c));
}
else{
if(tmp.length()!=0){
list.add(tmp.toString());
tmp=new StringBuilder();
}
}
}
if(tmp.length()!=0){
list.add(tmp.toString());
}
return list.toArray(new String[list.size()]);
}
}
05-10
9320
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)