208. 实现 Trie (前缀树)

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);
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值