参考
https://en.wikipedia.org/wiki/Trie
a trie, also called digital tree or prefix tree, is a kind of search tree—an ordered tree data structure used to store a dynamic set or associative array where the keys are usually strings
也叫前缀树, 特定情况下替代set 和map。这时候key是字符串。
LeetCode:208. Implement Trie (Prefix Tree)
LeetCode:211. Add and Search Word - Data structure design
LeetCode:212. Word Search II
下面我们就一步步来实现Trie,并做题
一、初步实现Trie树结构
208. Implement Trie (Prefix Tree)
https://leetcode.com/problems/implement-trie-prefix-tree/description/
#include<cstdio>
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
/**
* 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);
*/
const int letter_size=26;//字符集大小
struct TrieNode
{
TrieNode* children[letter_size]={0};
bool isWord = false;
TrieNode(){
}
~TrieNode(){
for(int i=0; i<letter_size; i++) if(children[i]) delete children[i];
}
};
struct Trie {
TrieNode* root;
/** Initialize your data structure here. */
Trie() {
root=new TrieNode();
}
~Trie(){
delete root;
}
int idx(char c)
{
return c - 'a';
}
/** Inserts a word into the trie. */
void insert(string word) {
TrieNode*p = root;
int len = word.length();
for(int i=0; i < len; i++){
int c = idx(word[i]);
if(!p->children[c])
p->children[c] = new TrieNode();
p = p->children[c];
}
p->isWord = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
TrieNode *p=root;
int len = word.length();
for(int i=0; i < len; i++){
p = p->children[idx(word[i])];
if(!p)
return false;
}
return p->isWord;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string word) {
TrieNode *p=root;
int len = word.length();
for(int i=0; i < len; i++){
p = p->children[idx(word[i])];
if(!p)
return false;
}
return true;
}
};
int main()
{
Trie trie;
trie.insert("apple");
cout<< trie.search("apple") << endl; // returns true
cout<< trie.search("app") << endl; // returns false
cout<< trie.startsWith("app") << endl; // returns true
trie.insert("app");
cout<< trie.search("app") << endl;; // returns true
return 0;
}
来源:oschina
链接:https://my.oschina.net/u/4305000/blog/4305276