关于字典树

#include<iostream>
using namespace std;

#define BASE 26
class node {
public:
    int flag;
    int next[BASE];
    void clear() {
        flag = 0;
        for (int i = 0; i < BASE; i++) {
            next[i] = 0;
        }
    }
} trie[10000];
int cnt, root;
void clearTrie() {
    cnt = 2, root = 1;
    trie[root].clear();
    return;
}

int getNewNode() {
    trie[cnt].clear();
    return cnt++;
}

void insert(string s) {
    int p = root;
    for (auto x : s) {
        int ind = x - 'a';
        if (trie[p].next[ind] == 0) trie[p].next[ind] = getNewNode();
        p = trie[p].next[ind];
    }
    trie[p].flag = 1;
    return;
}

bool search(string s) {
    int p = root;
    for (auto x : s) {
        int ind = x - 'a';
        p = trie[p].next[ind];
        if (p == 0) return false;
    }
    return trie[p].flag;
}

int main() {
    cout << "trie version 3 : " << endl;
    clearTrie();
    int op;
    string s;
    while (cin >> op >> s) {
        switch (op) {
        case 1: insert(s); break;
        case 2: cout << "search word = " << s << ", result : " << search(s);
        }
    }
    return 0;
}

/*
class Trie {
private:
    vector<Trie*> child;
    bool isEnd;
public:
    Trie() : child(26), isEnd(false) {
    }

    void insert(string word) {
        Trie* node = this;
        for (auto& ch : word) {
            if (node->child[ch - 'a'] == nullptr) node->child[ch - 'a'] = new Trie();
            node = node->child[ch - 'a'];
        }
        node->isEnd = true;
    }

    bool search(string word) {
        Trie* node = this;
        for (auto& ch : word) {
            if (node->child[ch - 'a'] == nullptr) return false;
            node = node->child[ch - 'a'];
        }
        return node->isEnd;
    }

    bool startsWith(string prefix) {
        Trie* node = this;
        for (auto& ch : prefix) {
            if (node->child[ch - 'a'] == nullptr) return false;
            node = node->child[ch - 'a'];
        }
        return true;
    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值