網(wǎng)站 301合肥全網(wǎng)推廣
前綴樹
- 題解1 STL
- 題解2 參考官方
Trie
(發(fā)音類似 “try”)或者說 前綴樹 是一種樹形數(shù)據(jù)結(jié)構(gòu),用于高效地存儲(chǔ)和檢索字符串?dāng)?shù)據(jù)集中的鍵。這一數(shù)據(jù)結(jié)構(gòu)有相當(dāng)多的應(yīng)用情景,例如自動(dòng)補(bǔ)完和拼寫檢查。
請(qǐng)你實(shí)現(xiàn) Trie
類:
Trie()
初始化前綴樹對(duì)象。void insert(String word)
向前綴樹中插入字符串word
。boolean search(String word)
如果字符串word
在前綴樹中,返回true
(即,在檢索之前已經(jīng)插入);否則,返回false
。boolean startsWith(String prefix)
如果之前已經(jīng)插入的字符串word
的前綴之一為prefix
,返回true
;否則,返回false
。
示例:
輸入
["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
輸出
[null, null, true, false, true, null, true]
解釋
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // 返回 True
trie.search("app"); // 返回 False
trie.startsWith("app"); // 返回 True
trie.insert("app");
trie.search("app"); // 返回 True
提示:
- 1 <=
word.length, prefix.length
<= 2000 word
和prefix
僅由小寫英文字母組成insert、search
和startsWith
調(diào)用次數(shù) 總計(jì) 不超過 3 ? 1 0 4 3 * 10^4 3?104 次
題解1 STL
class Trie {// map看存在map<string, int> m;// set看前綴set<string> k;
public:Trie() {}void insert(string word) {m[word] += 1;// k存儲(chǔ)前綴for(int i = 0; i <= word.size(); i++)k.insert(word.substr(0, i));}bool search(string word) {if(m.count(word))return true;return false;}bool startsWith(string prefix) {if(k.count(prefix))return true;return false;}
};/*** Your Trie object will be instantiated and called as such:* Trie* obj = new Trie();* obj->insert(word);* bool param_2 = obj->search(word);* bool param_3 = obj->startsWith(prefix);*/
題解2 參考官方
class Trie {vector<Trie*> children;bool isEnd;Trie* searchPrefix(string prefix){Trie* node = this;for(char ch : prefix){ch -= 'a';if(! node->children[ch]){return nullptr;}node = node->children[ch];}return node;}
public:Trie() : children(26), isEnd(false){}void insert(string word) {Trie* node = this;for(char ch : word){ch -= 'a';if(! node->children[ch])node->children[ch] = new Trie();node = node->children[ch];}// 這個(gè)word對(duì)應(yīng)的node 完整到底node->isEnd = true;}bool search(string word) {Trie* node = this->searchPrefix(word);// word不可以是前綴,所有要判斷isEndreturn node && node->isEnd;}bool startsWith(string prefix) {return this->searchPrefix(prefix) != nullptr;}
};