208. 实现 Trie (前缀树)
1.题目描述
实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。
示例:
说明:
1.你可以假设所有的输入都是由小写字母 a-z 构成的。
2.保证所有输入均为非空字符串。
2.思路
1.Trie 树的结点结构:有两个数据结构
(1)大小为26的数组:用来指向树中的每个节点。
(2)isEnd:指示该节点是否是单词的结尾。
2.向 Trie 树中插入键
从根节点root开始:
(1)如果插入的字符存在,则更新root,使其指向当前字符。
(2)如果插入的字符不存在,则新建一个节点,并更新root,使其指向当前字符。
复杂度分析:
时间复杂度:O(m),其中 m 为键长。在算法的每次迭代中,我们要么检查要么创建一个节点,直到到达键尾。只需要 m 次操作。
空间复杂度:O(m)。最坏的情况下,新插入的键和 Trie 树中已有的键没有公共前缀。此时需要添加 m 个结点,使用 O(m) 空间。
3.在 Trie 树中查找键
从根节点root开始:
(1)如果字符存在,则移动root到下一个节点
(2)如果字符不存在,直接返回false。
遍历完键的长度时,判断isEnd是否为true。直接返回isEnd。
复杂度分析:
时间复杂度 : O(m)。算法的每一步均搜索下一个键字符。最坏的情况下需要 m 次操作。
空间复杂度 : O(1)。
4.查找 Trie 树中的键前缀
该方法与在 Trie 树中搜索键时使用的方法非常相似。我们从根遍历 Trie 树,直到键前缀中没有字符,或者无法用当前的键字符继续 Trie 中的路径。与上面提到的“搜索键”算法唯一的区别是,到达键前缀的末尾时,总是返回 true。我们不需要考虑当前 Trie 节点是否用 “isEnd” 标记,因为我们搜索的是键的前缀,而不是整个键。
复杂度分析:
时间复杂度 : O(m)。算法的每一步均搜索下一个键字符。最坏的情况下需要 mm 次操作。
空间复杂度 : O(1)。
3.代码
class Trie {
public:
/** Initialize your data structure here. */
Trie() {
for(int i = 0;i < 26;++i){
next.push_back(NULL);
isEnd = false;
}
}
/** Inserts a word into the trie. */
void insert(string word) {
Trie* root = this;
for(auto &w : word){
if(root->next[w - 'a'] == NULL){
root->next[w - 'a'] = new Trie();
}
root = root->next[w - 'a'];//更新root指向当前字符
}
root->isEnd = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
Trie* root = this;
for(auto &w : word){
if(root->next[w - 'a'] == NULL){
return false;
}
root = root->next[w - 'a'];
}
return root->isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
Trie* root = this;
for(auto &p : prefix){
if(root->next[p - 'a'] == NULL){
return false;
}
root = root->next[p - 'a'];
}
return true;
}
private:
bool isEnd;
vector<Trie*> next;//Trie树的下一个节点
};
/**
* 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);
*/