您的位置:首页 > 其它

17.9设计一个函数,找到给定单词在一本书中的出现次数

2015-04-08 01:15 246 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐