字典树模板

把数据都存在一个TrieNode数组里,只保存其指向关系。

class TrieNode {
public:
    bool end;
    vector<int> son;
    TrieNode() {
        end = false;
        son = vector<int>(26, -1);
    }
};

class Trie {
public:
    vector<TrieNode> tree;

    Trie() {
        tree.push_back(TrieNode());
    }

    bool query(string& s) {
        int idx = 0;
        for(char c : s) {
            int to = tree[idx].son[c - 'a'];
            if (to == -1) return false;
            idx = to;
        }
        return tree[idx].end;
    }

    void insert(string &s) {
        int idx = 0;
        for (char c : s) {
            if (tree[idx].son[c - 'a'] == -1) {
                tree[idx].son[c - 'a'] = tree.size();
                tree.push_back(TrieNode());
            }
            idx = tree[idx].son[c - 'a'];
        }
        tree[idx].end = true;
    }
};
posted @   FlyingLight  阅读(11)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· .NET 原生驾驭 AI 新基建实战系列(一):向量数据库的应用与畅想
· Ai满嘴顺口溜,想考研?浪费我几个小时
· Browser-use 详细介绍&使用文档
· 软件产品开发中常见的10个问题及处理方法
点击右上角即可分享
微信分享提示