首页 > 其他 > 详细

实现Trie树

时间:2021-04-16 01:05:23      阅读:30      评论:0      收藏:0      [点我收藏+]

实现Trie树

class Trie {
public:
    struct Node {
        Node * son[26];
        bool is_end;

        Node() {
            for(int i = 0; i < 26; i ++ ) son[i] = nullptr;
            is_end = false;
        }
    }*root;
    /** Initialize your data structure here. */
    Trie() {
        root = new Node();
    }
    
    /** Inserts a word into the trie. */
    void insert(string word) {
        auto p = root;
        for(auto c : word) {
            int u = c - ‘a‘;
            if(!p->son[u]) p->son[u] = new Node();
            p = p->son[u];
        }
        p->is_end = true;
    }
    
    /** Returns if the word is in the trie. */
    bool search(string word) {
        auto p = root;
        for(auto c : word) {
            int u = c - ‘a‘;
            if(!p->son[u]) return false;
            p = p->son[u];
        }
        return p->is_end;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    bool startsWith(string prefix) {
        auto p = root;
        for(auto c : prefix) {
            int u = c - ‘a‘;
            if(!p->son[u]) return false;
            p = p->son[u];
        }
        return true;
    }
};

/**
 * 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);
 */
  • new方法调用很耗时,在做笔试题时很容易超时,要么一次性将需要的内存开出来,要么用数组模拟指针

前缀统计

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

const int N = 1e6 + 10;

int n, m;
char str[N];

int son[N][26], cnt[N], idx;

void insert(char *str)  // 插入字符串
{
    int p = 0;
    for (int i = 0; str[i]; i ++ )
    {
        int u = str[i] - ‘a‘;
        if (!son[p][u]) son[p][u] = ++ idx;
        p = son[p][u];
    }
    cnt[p] ++ ;
}

int query(char *str)  // 查询有多少个字符串是 T 的前缀
{
    int p = 0, res = 0;
    for (int i = 0; str[i]; i ++ )
    {
        int u = str[i] - ‘a‘;
        if (!son[p][u]) return res;
        p = son[p][u];
        res += cnt[p];
    }
    return res;
}


int main() {
    scanf("%d%d", &n, &m);
    while (n -- ){
        scanf("%s", str);
        insert(str);
    }
    
    while (m -- ) {
        scanf("%s", str);
        printf("%d\n", query(str));
    }
    
    return 0;
}

实现Trie树

原文:https://www.cnblogs.com/huhu555/p/14665118.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!