题目
连着刷了好几天的hashmap,终于是有点起色,力扣中等题目,10分钟写完,哈哈哈哈
class WordsFrequency {
private HashMap<String,Integer> map = new HashMap<String,Integer>() ;
public WordsFrequency(String[] book) {
for(String s:book){
if(map.containsKey(s)){
map.put(s,map.get(s)+1);
}else{
map.put(s,1);
}
}
}
public int get(String word) {
if(map.containsKey(word)){
return map.get(word);
}else{
return 0;
}
}
}
思路
首先字符串数组存入到哈希表中,以单个字符为键,出现的次数为值,如果map中存在该键,就将其中值+1,如果不存在该键,就存入到map中,并把值设置为1。最后调用get()方法来获取频率。