字典树

链表版字典树

class Trie
{
    Trie* next[26];
    int num;
public:
    Trie() {
        for (int i = 0; i < 26; ++i) next[i] = NULL;
        num = 0;
    }
    void insert(char *s) {
        Trie *p = this;
        for (int i = 0; s[i]; ++i) {
            int t = s[i]-'a';
            if (p->next[t] == NULL) p->next[t] = new Trie;
            p = p->next[t];
            ++ p->num;
        }
    }
    int find(char *s) {
        Trie *p = this;
        for (int i = 0; s[i]; ++i) {
            int t = s[i]-'a';
            if (p->next[t] == NULL) return 0;
            p = p->next[t];
        }
        return p->num;
    }
};

数组版字典树

为了便于封装,此处用 vector 代替了数组。

#include <vector>
using namespace std;
class Trie
{
    int cnt;
    vector<vector<int> > tree;
    vector<int> num;
public:
    Trie(int n) {
        cnt = 0;
        tree.resize(n, vector<int>(26));
        num.resize(n);
    }
    void insert(char *s) {
        int p = 0;
        for (int i = 0; s[i]; ++i) {
            int t = s[i]-'a';
            if (!tree[p][t]) tree[p][t] = ++cnt;
            p = tree[p][t];
            ++num[p];
        }
    }
    int find(char *s) {
        int p = 0;
        for (int i = 0; s[i]; ++i) {
            int t = s[i]-'a';
            if (!tree[p][t]) return 0;
            p = tree[p][t];
        }
        return num[p];
    }
};

测试

hdu1251统计难题(字典树)
leetcode5714. 替换字符串中的括号内容

posted @ 2021-03-12 23:50  Zewbie  阅读(59)  评论(0)    收藏  举报