cc 17.9 hashtable应用
首先需要考虑这个函数被调用的次数,如果只查询一次,直接遍历整本书,计算给定单词次数。时间只能是O(N)。
正常情况下通常需要可以多次调用
这样pre-processing the book,use hashtable to store word, frequency. then we can easily look up by O(1) time.
代码很简单,就是建立hashtable,然后查找
其中:word忽略大小写区别,所以可以都转换为小写,trim() != “ “
public int findword(Hashtable<String, Integer> map, String word){
if(word == null || map == null) return -1; // wrong situation
/*****here we ignore diff between uppercase and lowercase****/
word = word.toLowerCase();
if(map.containsKey(word)){
return map.get(word);
}
return 0;
}
//set up hashtable for the book
private Hashtable<String, Integer> setupDic(String[] book){
Hashtable<String, Integer> map = new Hashtable<String, Integer>();
for(String s : book){
/*****corner case******************/
if(s.trim() == "") continue;
/********************************/
s = s.toLowerCase();
if(map.containsKey(s)){
map.put(s, map.get(s) + 1);
}else map.put(s, 1);
}
return map;
}