Leetcode常用模板-字典树

本文详细介绍了一种高效的数据结构——字典树(Trie),并提供了插入和搜索字符串的具体实现。字典树能有效存储大量字符串,尤其适用于词汇表、IP路由选择等场景,通过递归方式构建节点,实现快速查找。
const int char_size = 26;

struct charTreeNode {
    int check;
    charTreeNode* children[char_size];
    charTreeNode() {
        check = 0;
        for (int i = 0; i < char_size ; i++) {
            children[i] = NULL;
        }
    }
};
struct charTree {
    charTreeNode* root = new charTreeNode();
    void insertNode(string s) {
        int l = s.length();
        charTreeNode* node = root;
        for (int i = 0; i < l; i++) {
            int c = s[i] - 'a';
            if (node -> children[c] == NULL) node -> children[c] = new charTreeNode();
            node = node -> children[c];
        }
        node -> check = 1;
    }
    string searchTree(string s) {
        int l = s.length();
        string ans = "";
        charTreeNode* node = root;
        for (int i = 0; i < l; i++) {
            int c = s[i] - 'a';
            ans += s[i];
            if (node == NULL || node -> children[c] == NULL) return s;
            node = node -> children[c];
            if (node -> check == 1) return ans;
        }
        return s;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值