【LeetCode-树】实现 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

题目链接: https://leetcode-cn.com/problems/implement-trie-prefix-tree/

思路

Trie 树每个节点存储数组,在这题中数组长度为 26,如下:

struct TrieNode {
    bool isEnd; //该结点是否是一个串的结束
    TrieNode* next[26]; //字母映射表
};

插入、匹配类似于链表操作,具体可以看这篇题解
代码如下:

class Trie {
public:
    bool isEnd;
    Trie* next[26];

    /** Initialize your data structure here. */
    Trie() {
        isEnd = false;
        memset(next, 0, sizeof(next));
    }
    
    /** Inserts a word into the trie. */
    void insert(string word) {
        Trie* node = this;
        for(int i=0; i<word.length(); i++){
            char c = word[i];
            if(node->next[c-'a']==nullptr){ // 没有匹配上,开辟新节点
                node->next[c-'a'] = new Trie();
                // node = node->next[c-'a'];    // 这一句要写在外面
            }
            node = node->next[c-'a'];   // 匹配上了,匹配下一个
        }
        node->isEnd = true;
    }
    
    /** Returns if the word is in the trie. */
    bool search(string word) {
        Trie* node = this;
        for(int i=0; i<word.length(); i++){
            char c = word[i];
            if(node->next[c-'a']!=nullptr){
                node = node->next[c-'a'];
            }else return false;
        }
        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(int i=0; i<prefix.length(); i++){
            char c = prefix[i];
            if(node->next[c-'a']!=nullptr){
                node = node->next[c-'a'];
            }else return false;
        }
        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);
 */
原文地址:https://www.cnblogs.com/flix/p/12858779.html