【力扣hot100题】(053)实现Trie(前缀树)

本来感觉没什么难度的,和之前那道LRU差不多,结果看了题解……emmm只有我真的写了个树的结构体吗…………

class Trie {
public:
    struct TreeNode{
        char val;
        map<char,TreeNode*> children;
        TreeNode() : val(0) {}
        TreeNode(char x) : val(x) {}
    };
    TreeNode* root;
    Trie() {
        root=new TreeNode();
    }
    
    void insert(string word) {
        int loc=0;
        TreeNode* now=root;
        while(now->children[word[loc]]){
            now=now->children[word[loc]];
            loc++;
        }
        while(loc<word.size()){
            TreeNode* newnode=new TreeNode(word[loc]);
            now->children[word[loc]]=newnode;
            now=newnode;
            loc++;
        }
        TreeNode* newnode=new TreeNode('0');
        now->children['0']=newnode;
    }
    
    bool search(string word) {
        TreeNode* now=root;
        for(int i=0;i<word.size();i++){
            if(now->children.find(word[i])==now->children.end()) return 0;
            else now=now->children[word[i]];
        }
        if(now->children['0']) return 1;
        return 0;
    }
    
    bool startsWith(string prefix) {
        TreeNode* now=root;
        for(int i=0;i<prefix.size();i++){
            if(now->children.find(prefix[i])==now->children.end()) return 0;
            else now=now->children[prefix[i]];
        }
        return 1;
    }
};

/**
 * 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);
 */

总之写的好像有些跑题了,好吧看来这题和LRU还是有不同的,

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值