程序员面试金典 - 面试题 16.02. 单词频率(哈希表/Trie树)

1. 题目

设计一个方法,找出任意指定单词在一本书中的出现频率。

你的实现应该支持如下操作:

  • WordsFrequency(book)构造函数,参数为字符串数组构成的一本书
  • get(word)查询指定单词在数中出现的频率
示例:
WordsFrequency wordsFrequency = new WordsFrequency(
{"i", "have", "an", "apple", "he", "have", "a", "pen"});
wordsFrequency.get("you"); //返回0"you"没有出现过
wordsFrequency.get("have"); //返回2"have"出现2次
wordsFrequency.get("an"); //返回1
wordsFrequency.get("apple"); //返回1
wordsFrequency.get("pen"); //返回1

提示:
book[i]中只包含小写字母
1 <= book.length <= 100000
1 <= book[i].length <= 10
get函数的调用次数不会超过100000

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/words-frequency-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 解题

2.1 哈希解法

class WordsFrequency {
	unordered_map<string,int> m;
public:
    WordsFrequency(vector<string>& book) {
    	for(auto& s : book)
    		m[s]++;
    }
    
    int get(string word) {
    	return m[word];
    }
};

2.2 Trie树

参考Trie树

class Trie
{
public:
	unordered_map<char,Trie*> next;
	bool isEnd = false;
	int count = 0;

	void insert(string& s)
	{
		Trie *root = this;
		for(char ch : s)
		{
			if(!(root->next).count(ch))
			{
				Trie* node = new Trie();
				root->next.insert(make_pair(ch,node));
			}
			root = root->next[ch];
		}
		root->isEnd = true;
		root->count++;
	}

	int search(string& s)
	{
		Trie * root = this;
		for(char ch : s)
		{
			if(!(root->next).count(ch))
			{
				return 0;
			}
			root = root->next[ch];
		}
		if(root->isEnd)
			return root->count;
		return 0;
	}
};
class WordsFrequency {
	Trie *t;
public:
    WordsFrequency(vector<string>& book) {
    	t = new Trie();
    	for(string& b : book)
    		t->insert(b);
    }
    
    int get(string word) {
    	return t->search(word);
    }
};

在这里插入图片描述

发布了782 篇原创文章 · 获赞 1135 · 访问量 30万+

猜你喜欢

转载自blog.csdn.net/qq_21201267/article/details/105165335