力扣208. 实现 Trie (前缀树) 字典树模板 C++

该题是字典树的典型例题,可以作为字典树模板背下来。在需要频繁查找字符串或字符前缀集合时可以用到,牺牲空间达到O(n)的查找时间。


题目
Trie(发音类似 “try”)或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完和拼写检查。

请你实现 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

提示:
1 <= word.length, prefix.length <= 2000
word 和 prefix 仅由小写英文字母组成
insert、search 和 startsWith 调用次数 总计 不超过 3 * 10^4 次

代码(模板)

class Trie {
private:
    vector<Trie *> children;//指向26棵子树的指针数组 表示'a'~'z'
    bool haveWord;//表示该子树是否为字符串结尾 
    //即该结点是否为已有的某个字符串的最后一个字符
public:
    Trie():children(26),haveWord(false) {}//使用构造函数初始值列表初始化
    
    void insert(string word) {//向字典树插入一个单词
        Trie *node=this;
        for(auto &aChar : word){
            if(!node->children[aChar-'a']) node->children[aChar-'a']=new Trie();//这一层的字典树的子树中,还没有这个字母,那么新建一个
            node=node->children[aChar-'a'];//树中已经有该字母
        }
        node->haveWord=true;
    }
    
    bool search(string word) {//查找字典树中有没有这个单词
        Trie *node=this;
        for(auto &aChar : word){
            if(!node->children[aChar-'a']) return false;//字典树的这一层子树中,还没有这个字母,查找失败
            node=node->children[aChar-'a'];
        }
        return node->haveWord;
    }
    
    bool startsWith(string prefix) {//查找字典树中有没有以这个字符串为前缀的单词
        Trie *node=this;
        for(auto &aChar : prefix){
            if(!node->children[aChar-'a']) return false;//这一层的字典树的子树中,还没有这个字母,查找失败
            node=node->children[aChar-'a'];
        }
        return true;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_43739821/article/details/130115902
今日推荐