Implement Trie (Prefix Tree)

406 篇文章 0 订阅
406 篇文章 0 订阅

1,题目要求

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

Example:

Trie trie = new Trie();

trie.insert("apple");
trie.search("apple");   // returns true
trie.search("app");     // returns false
trie.startsWith("app"); // returns true
trie.insert("app");   
trie.search("app");     // returns true

Note:

  • You may assume that all inputs are consist of lowercase letters a-z.
  • All inputs are guaranteed to be non-empty strings.

使用insert,search和startsWith方法实现trie。

2,题目思路

对于这道题,题目的要求是实现一个Prefix Tree,即前缀树。


Trie,又称前缀树或字典树,是一种有序树,用于保存关联数组,其中的键通常是字符串。与二叉查找树不同,键不是直接保存在节点中,而是由节点在树中的位置决定。一个节点的所有子孙都有相同的前缀,也就是这个节点对应的字符串,而根节点对应空字符串。一般情况下,不是所有的节点都有对应的值,只有叶子节点和部分内部节点所对应的键才有相关的值。
Trie可以看作是一个确定有限状态自动机,尽管边上的符号一般是隐含在分支的顺序中的。

在这里插入图片描述
参考文章:
Trie (Prefix Tree) 前缀树


在实现上,我们创建一个含有26个指针的节点,用来构建一个类似于26叉树的形式。
其中,memset用于将S所指向的某一块内存中的内容全部设置为成指定的ASCII值,块的大小由第三个参数所决定,因此,这个函数通常为新申请的内存做初始化工作,其返回值为指向S的指针。

void *memset(void *s,int c,size_t n)

参考文章:

memset函数使用方法

具体操作详见部分3。

3,代码实现

int x = []() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    return 0;
}();

class TrieNode {
public:
    TrieNode *children[26];
    bool isWord;
    
    TrieNode(bool b = false){
        memset(children, 0, sizeof(children));
        isWord = b;
    }
};

class Trie {
public:
    /** Initialize your data structure here. */
    Trie() {
        root = new TrieNode();
    }
    
    /** Inserts a word into the trie. */
    void insert(string word) {
        TrieNode *p = root;
        for(auto &c : word){
            if(p->children[c - 'a'] == NULL)
                p->children[c - 'a'] = new TrieNode();
            p = p->children[c - 'a'];
        }
        p->isWord = true;
    }
    
    /** Returns if the word is in the trie. */
    bool search(string word) {
        TrieNode *p = findWord(word);
        return p!= NULL && p->isWord;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    bool startsWith(string prefix) {
        return findWord(prefix) != NULL;
    }

private:
    TrieNode* root;

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

/**
 * 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);
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值