从书中查找某个单词出现的频率

2 篇文章 0 订阅

设计算法,找出一本书中任一给定的词汇的频率。

Design a method to find the frequency of occurrences of any given word in a

book. 


对于只找出一个单词的频率和找出多个单词的频率解法不同。

SOLUTION
The 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 Query
In 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 Queries
In 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;
	}



Note: a problem like this is relatively easy. Thus, the interviewer is going to be
looking heavily at how careful you are. Did you check for error conditions?
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值