Implement Trie (Prefix Tree)

Trie

Trie 就是一棵字典树,根节点为空,从根节点出发到任意一个叶子节点的路径都是一个单词,也就是当前节点的父节点往上一直到根节点的路径是这个单词的前缀,每个节点分别维护一个数组记录后续子节点以及从根节点到当前节点的路径是否为一个单词。
这个题目的意思就是实现这样一棵字典树,插入一个单词,搜索一个单词,以及使用前缀搜索。

题意及条件

题目指定只包含a~z的小写字母,实现单词的插入,单词的搜索,以及前缀的搜索功能即可。

代码实现

class TrieNode {
public:
    // Initialize your data structure here.
    bool isWord;
    vector<TrieNode*> nextNodes;
    TrieNode() {
       this->isWord = false;
       this->nextNodes.resize(26,NULL);
    }
};

class Trie {
public:
    Trie() {
        root = new TrieNode();
    }

    // Inserts a word into the trie.
    void insert(string word) {
        if(word=="")
            return;
        TrieNode* cur=root;
        for(int i=0;i<word.size();++i){
            if(cur->nextNodes[word[i]-'a']!=NULL){
                if(i==word.size()-1){
                    (cur->nextNodes[word[i]-'a'])->isWord = true;
                    return;
                };
            }else{
                cur->nextNodes[word[i]-'a'] = new TrieNode() ;
                 if(i==word.size()-1){
                    (cur->nextNodes[word[i]-'a'])->isWord = true;
                    return;
                };
            }

            cur =  cur->nextNodes[word[i]-'a'] ;
        }

    }

    // Returns if the word is in the trie.
    bool search(string word) {
        if(word=="")
            return true;
        TrieNode* cur = root;
        for(int i=0;i<word.size();++i){
            if(cur->nextNodes[word[i]-'a']!=NULL){
                if(i==word.size()-1){
                    return (cur->nextNodes[word[i]-'a'])->isWord;
                }else
                    cur = cur->nextNodes[word[i]-'a'];
            }else
                return false;
        }
        return false;

    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    bool startsWith(string prefix) {
        if(prefix=="")
            return true;
        TrieNode* cur = root;
        for(int i=0;i<prefix.size();++i){
           if(cur->nextNodes[prefix[i]-'a']!=NULL){
                if(i==prefix.size()-1){
                    return true;
                }else
                    cur = cur->nextNodes[prefix[i]-'a'];
            }else
                return false;
        }
    }

private:
    TrieNode* root;
};

有的同学可能会发现代码的重复,这样其实可以提供一个通用的方法,用于查找前缀,就可以大大简化上述代码。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值