题目
原文:
Design a method to find the frequency of occurrences of any given word in a book.
译文:
设计一个方法找到给定单词在一本书中的出现次数。
解答
若只是查询一次,先进行预处理,事先处理好,放在一个Hashtable里,在通过O(1)的时间进行查询即可。
代码如下:
class Q19_8{
public static void main(String[] args){
}
public static Hashtable<String,Integer> setupDictionary(String[] book){
Hashtable<String,Integer> table=new Hashtable<String,Integer>();
for(String word:book){
word=word.toLowerCase();
if(word.trim()!=""){
if(!table.cintainsKey(word)){
table.put(word,0);
}
table.put(word,table.get(word)+1);
}
}
return table;
}
public static int lookupWord(Hashtable<String,Integer> table,String word){
if(table==null||word==null){
return -1;
}
word=word.toLowerCase();
if(table.containsKey(word)){
return table.get(word);
}
return 0;
}
}---EOF---
本文介绍了一种高效的方法来计算一本书中特定单词的出现次数。该方法首先对整本书的内容进行预处理并存储在一个哈希表中,之后可以快速查询任意单词的出现频率。
2789

被折叠的 条评论
为什么被折叠?



