Leetcode题解 - 208. Implement Trie (Prefix Tree)

本文介绍了一种高效的数据结构——Trie树(字典树或前缀树),并提供了详细的实现方法,包括插入(insert)、搜索(search)及前缀匹配(startsWith)等功能。文章通过实例解释了如何构建Trie树,并给出了C++代码示例。

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

Implement a trie with insert, search, and startsWith methods.
Note:
You may assume that all inputs are consist of lowercase letters a-z.

戳我

Trie即字典树或者前缀树,

如给出字符串”abc”,”ab”,”bd”,”dda”,根据该字符串序列构建一棵Trie树。则构建的树如下:

这里写图片描述

为了描述这个数据结构,先建立TrieNode这个类,即字典树的节点,每个结点包括26个孩子结点,因为总共有26个英文字母(假设单词都是小写字母组成)。

插入方法就是对于某个字符串,将其插入到一颗字典树的具体操作应该是从root节点开始,逐个查找对应字母的节点是否存在,如果不存在则创建对应的字典树节点,最后将isword即对应是否构成一个完整的词语。

对于search和startWith方法,可以先抽象出一个find方法,返回最后一个字母所在的节点,之后对于search方法就是判断返回的节点是否为空(单词不存在)以及返回的节点是否构成完整的单词,而startWith方法就是只判断是否为空就行了。

class TrieNode{
public:
    TrieNode *next[26];//指向各个子树的指针  
    TrieNode(bool b=false){
        memset(next,0,sizeof(next));
        isword=b;//是否构成完整的单词
    }
    bool isword;

};

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

    }
public:
    /** Initialize your data structure here. */
    Trie() {
        root=new TrieNode();
    }

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

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

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

/**
 * 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);
 */

ref:

http://blog.csdn.net/hackbuteer1/article/details/7964147

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值