程序员面试金典 - 面试题 16.02. 单词频率(哈希表/Trie树)
生活随笔
收集整理的這篇文章主要介紹了
程序员面试金典 - 面试题 16.02. 单词频率(哈希表/Trie树)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
文章目錄
- 1. 題目
- 2. 解題
- 2.1 哈希解法
- 2.2 Trie樹
1. 題目
設(shè)計(jì)一個(gè)方法,找出任意指定單詞在一本書中的出現(xiàn)頻率。
你的實(shí)現(xiàn)應(yīng)該支持如下操作:
- WordsFrequency(book)構(gòu)造函數(shù),參數(shù)為字符串?dāng)?shù)組構(gòu)成的一本書
- get(word)查詢指定單詞在數(shù)中出現(xiàn)的頻率
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/words-frequency-lcci
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。
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);} };總結(jié)
以上是生活随笔為你收集整理的程序员面试金典 - 面试题 16.02. 单词频率(哈希表/Trie树)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 剑指Offer - 面试题51. 数组中
- 下一篇: LeetCode 355. 设计推特(哈