[leetcode]208.实现Trie(前缀树)

题目

实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。

示例

Trie trie = new Trie();

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

分析:

三个功能

insert

将一个单词插入前缀树。

search

给一个单词搜索是否在前缀树中。

startsWith

给一个字符串,看前缀树中是否有单词以此为前缀。

两个变量

Trie* next[26]isEnd。前者是一个指针数组,即next数组中有26个指针,每个指针指向一个Trie对象。所有元素初始为空指针。当insert时,若当前字符代表的位置为空时,则创建新的Trie对象,让该位置指向这个新的对象,新的对象中同样包含这样两个元素。后者表示当前对象代表的字符,是否为一个单词的最后一个字符,这个变量用来search。

代码

class Trie {
private:
    Trie* next[26] = { nullptr };
    bool isEnd = false;
public:
    /** Initialize your data structure here. */
    Trie() {}
    
    /** Inserts a word into the trie. */
    void insert(string word) {
        Trie* node = this;		  // node指向当前对象
        for ( auto c : word ) {
            int index = c - 'a';
            if ( node->next[index] == nullptr ) {
                node->next[index] = new Trie();
            }

            node = node->next[index];
        }

        node->isEnd = true;
    }
    
    /** Returns if the word is in the trie. */
    bool search(string word) {
        Trie* node = this;
        for ( auto c : word ) {
            int index = c - 'a';
            if ( node->next[index] == nullptr ) {
                return false;
            }
            
            node = node->next[index];
        }

        return node->isEnd;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    bool startsWith(string prefix) {
        Trie* node = this;
        for ( auto c : prefix ) {
            int index = c - 'a';
            if ( node->next[index] == nullptr ) {
                return false;
            }

            node = node->next[index];
        }

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值