设计算法,找出一本书中任一给定的词汇的频率。
Design a method to find the frequency of occurrences of any given word in a
book.
对于只找出一个单词的频率和找出多个单词的频率解法不同。
SOLUTIONThe first question – which you should ask your interviewer – is if you’re just asking for a single
word (“single query”) or if you might, eventually, ask for the frequency of multiple words
(“repetitive queries”).
仅一个单词:
逐个词汇的遍历整本书,计算词汇出现的频率。花费了O(n) 的时间。由于必须遍历一整本书,所以这是最好的方式。
Solution: Single QueryIn this case, we simple go through the book, word by word, and count the number of times
that a word appears. This will take O(n) time. We know we can’t do better than that, as we
must look at every word in the book.
求多个单词的频率:
创建一个从词汇映射到频率的hash table。伪代码如下:
Solution: Repetitive QueriesIn this case, we create a hash table which maps from a word to a frequency. Our pseudo code
is then like this:
Hashtable setupDictionary(string[] book) {
Hashtable table = new Hashtable();
foreach (string word in book) {
if (!table.contains(word)) {
table.add(word, 0);
}
table[word] = table[word] + 1;
}
}
int getFrequency(Hashtable table, string word) {
if (table == null or word == null) {
return -1;
}
if (table.contains(word)) {
return table[word];
}
return 0;
}
looking heavily at how careful you are. Did you check for error conditions?