Implement Trie (Prefix Tree)

本文介绍如何使用C++实现Trie树的基本操作,包括插入、搜索和前缀匹配等功能。通过详细解析Trie树节点结构及核心算法,帮助读者理解Trie树的工作原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目名称
208. Implement Trie (Prefix Tree)

描述
Implement a trie with insert, search, and startsWith methods.

Note:
You may assume that all inputs are consist of lowercase letters a-z.

分析
  字典树(Trie),又称单词查找树,Trie树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较,查询效率比哈希树高。
  题目中要求我们实现三个函数:insert, search, and startsWith,并且所有的输入都是有小写字母组成的字符串。至于Trie树的实现,可以用数组,也可以用指针动态分配,考虑到小写字母共有26个,就用了数组,静态分配空间。

结点的数据结构如下:

class TrieNode {
public:
    //存放指向下一个字符的指针数组
    vector<TrieNode*> next;
    //标记该节点是否为一个字符串的结尾
    bool is_end;
    //constructor,初始化next的大小为26,is_end为false
    TrieNode():next(26),is_end(false){}
};

C++代码

class TrieNode {
public:
    // Initialize your data structure here.
    vector<TrieNode*> next;
    bool is_end;
    TrieNode():next(26),is_end(false){}
};

class Trie {
public:
    Trie() {
        root = new TrieNode();
    }

    // Inserts a word into the trie.
    void insert(string word) {
        TrieNode *p = root;
        int k = 0;
        for(int i=0;i<word.size();++i) {
            k = word[i]-'a';
            if(p->next[k] == NULL){
                p->next[k] = new TrieNode();
            }
            p = p->next[k];
        }
        p->is_end = true;
    }

    // Returns if the word is in the trie.
    bool search(string word) {
        TrieNode *p = find(word);
        return p!=NULL && p->is_end;
    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    bool startsWith(string prefix) {
        return find(prefix) != NULL;
    }

private:
    TrieNode* root;
    TrieNode* find(string key)
    {
        TrieNode *p = root;
        for(int i = 0; i < key.size() && p != NULL; ++ i)
            p = p -> next[key[i] - 'a'];
        return p;
    }
};

总结
  这里只是字典树的一个小的应用,其他的功能我会在接下来的文章中给大家分享。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值