实现 Trie (前缀树)
LeetCode 上的「208. 实现 Trie (前缀树)」
前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完和拼写检查。
请你实现 Trie 类:
- Trie() 初始化前缀树对象。
- void insert(String word) 向前缀树中插入字符串 word 。
- boolean search(String word) 如果字符串 word 在前缀树中,返回 true(即,在检索之前已经插入);否则,返回 false 。
- boolean startsWith(String prefix) 如果之前已经插入的字符串 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
Trie 树
Trie 树(又叫「前缀树」或「字典树」)是一种用于快速查询「某个字符串/字符前缀」是否存在的数据结构。
其核心是使用「边」来代表有无字符,使用「点」来记录是否为「单词结尾」以及「其后续字符串的字符是什么」。
const int N = 100009; // 直接设置为十万级
class Trie {
private:
vector<array<int, 26>> trie;
vector<int> count;
int index;
public:
Trie() {
trie.resize(N, array<int, 26>());
count.resize(N);
index = 0;
}
void insert(string s) {
int p = 0;
for (int i = 0; i < s.length(); i++) {
int u = s[i] - 'a';
if (trie[p][u] == 0) trie[p][u] = ++index;
p = trie[p][u];
}
count[p]++;
}
bool search(string s) {
int p = 0;
for (int i = 0; i < s.length(); i++) {
int u = s[i] - 'a';
if (trie[p][u] == 0) return false;
p = trie[p][u];
}
return count[p] != 0;
}
bool startsWith(string s) {
int p = 0;
for (int i = 0; i < s.length(); i++) {
int u = s[i] - 'a';
if (trie[p][u] == 0) return false;
p = trie[p][u];
}
return true;
}
};
- 时间复杂度: Trie树的每次调用时间复杂度取决于入参字符串的长度。复杂度为O(Len) 。
- 空间复杂度:二维数组的高度为n ,字符集大小为k 。复杂度为 O(nk)。
TrieNode
相比二维数组,更加常规的做法是建立TreeNode 结构节点。
随着数据的不断插入,根据需要不断创建TreeNode节点。
class Trie {
private:
struct TrieNode {
bool end;
vector<TrieNode*> children;
TrieNode() : end(false), children(26, nullptr) {}
};
TrieNode* root;
public:
Trie() {
root = new TrieNode();
}
void insert(string s) {
TrieNode* p = root;
for (char c : s) {
int u = c - 'a';
if (!p->children[u]) {
p->children[u] = new TrieNode();
}
p = p->children[u];
}
p->end = true;
}
bool search(string s) {
TrieNode* p = root;
for (char c : s) {
int u = c - 'a';
if (!p->children[u]) {
return false;
}
p = p->children[u];
}
return p->end;
}
bool startsWith(string s) {
TrieNode* p = root;
for (char c : s) {
int u = c - 'a';
if (!p->children[u]) {
return false;
}
p = p->children[u];
}
return true;
}
};
- 时间复杂度: Trie树的每次调用时间复杂度取决于入参字符串的长度。复杂度为O(Len) 。
- 空间复杂度:结点数量为 n,字符集大小为k 。复杂度为O(nk) 。
两种方式的对比
使用「二维数组」的好处是写起来飞快,同时没有频繁new对象的开销。但是需要根据数据结构范围估算我们的「二维数组」应该开多少行。
坏处是使用的空间通常是「TrieNode」方式的数倍,而且由于通常对行的估算会很大,导致使用的二维数组开得很大,如果这时候每次创建Trie对象时都去创建数组的话,会比较慢,而且当样例多的时候甚至会触发 GC(因为OJ每测试一个样例会创建一个Trie对象)。
因此还有一个小技巧是将使用到的数组转为静态,然后利用index自增的特性在初始化Trie时执行清理工作 & 重置逻辑。
class Trie {
private:
/ 以下 static 成员独一份,被创建的多个 Trie 共用
static const int N = 100009; // 直接设置为十万级
static array<array<int, 26>, N> trie;
static array<int, N> count;
static int index;
public:
// 在构造方法中完成重置 static 成员数组的操作
// 这样做的目的是为减少 new 操作(无论有多少测试数据,上述 static 成员只会被 new 一次)
Trie() {
for (int row = index; row >= 0; row--) {
for (int col = 0; col < 26; col++) {
trie[row][col] = 0;
}
}
for (int i = 0; i < N; i++) {
count[i] = 0;
}
index = 0;
}
void insert(string s) {
int p = 0;
for (char c : s) {
int u = c - 'a';
if (trie[p][u] == 0) {
trie[p][u] = ++index;
}
p = trie[p][u];
}
count[p]++;
}
bool search(string s) {
int p = 0;
for (char c : s) {
int u = c - 'a';
if (trie[p][u] == 0) {
return false;
}
p = trie[p][u];
}
return count[p] != 0;
}
bool startsWith(string s) {
int p = 0;
for (char c : s) {
int u = c - 'a';
if (trie[p][u] == 0) {
return false;
}
p = trie[p][u];
}
return true;
}
};