程序员面试金典 - 面试题 16.02. 单词频率(哈希表/Trie树)
生活随笔
收集整理的這篇文章主要介紹了
程序员面试金典 - 面试题 16.02. 单词频率(哈希表/Trie树)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 1. 題目
- 2. 解題
- 2.1 哈希解法
- 2.2 Trie樹
1. 題目
設計一個方法,找出任意指定單詞在一本書中的出現頻率。
你的實現應該支持如下操作:
- WordsFrequency(book)構造函數,參數為字符串數組構成的一本書
- get(word)查詢指定單詞在數中出現的頻率
來源:力扣(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);} };總結
以上是生活随笔為你收集整理的程序员面试金典 - 面试题 16.02. 单词频率(哈希表/Trie树)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 剑指Offer - 面试题51. 数组中
- 下一篇: LeetCode 355. 设计推特(哈