Trie树

Posted by Liao on 2020-05-09

Trie树

Trie树,又称字典树、前缀树,是一种树形结构,它是一种专门处理字符串匹配的数据结构,用来解决在一组字符串集合中快速查找某个字符串的问题。

Trie树的特点

  • 根节点不包含字符,根节点外的每一个结点表示一个字母
  • 从根节点到某一个结点连起来的路径,成为有一个字符串
  • 每个节点的子节点所包含的字符不相同

插入&查找

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class Trie {
private:
vector<Trie*>children;
bool isEnd;
Trie* searchPrefix(string prefix) {
Trie* node = this;
for(char c : prefix) {
c -= 'a';
if(node->children[c] == nullptr) {
return nullptr;
}
node = node->children[c]; // 下一个结点
}
return node;
}

public:
/** Initialize your data structure here. */
Trie() : children(26), isEnd(false) {}

/** Inserts a word into the trie. */
void insert(string word) {
Trie* node = this;
for(char c : word) {
c -= 'a';
if(node->children[c] == nullptr) {
node->children[c] = new Trie();
}
node = node->children[c];
}
node->isEnd = true;
}

/** Returns if the word is in the trie. */
bool search(string word) {
Trie* node = this->searchPrefix(word);
return node != nullptr && node->isEnd;
}

/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
return this->searchPrefix(prefix) != nullptr;
}
};

/**
* 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);
*/

https://juejin.im/post/5c2c096251882579717db3d2#heading-9

https://www.cnblogs.com/huangxincheng/archive/2012/11/25/2788268.html