trie字典树

字典树关键:
每个节点包含整个字母表,空间占用浪费很多。
trie的形状和插入顺序无关,相同字符串集的trie树是相同的

参考:Trie Tree 的实现 (适合初学者)

代码编写注意:构造函数要对next数组初始化指针为空,否则访问next数组时会出现异常

Trie() {
    memset(next, 0, sizeof(next)); // 这里的memset必须要加,否则访问node->next[index]会出现指针异常
}
class Trie {
private:
    bool isEnd = false;
    Trie* next[26];
public:
    Trie() {
        memset(next, 0, sizeof(next)); // 这里的memset必须要加,否则访问node->next[index]会出现指针异常
    }
    
    void insert(string word) {
        Trie* node = this;
        for (char c : word) {
            if (node->next[c - 'a'] == NULL) node->next[c - 'a'] = new Trie();
            node = node->next[c - 'a'];
        }
        node->isEnd = true;
    }
    
    bool search(string word) {
        Trie* node = this;
        for (char c : word) {
            if (node->next[c - 'a'] == NULL) return false;
            node = node->next[c - 'a'];
        }
        return node->isEnd;
    }
    
    bool startsWith(string prefix) {
        Trie* node = this;
        for (char c : prefix) {
            if (node->next[c - 'a'] == NULL) return false;
            node = node->next[c - 'a'];
        }
        return true;
    }
};

你可能感兴趣的:(算法,leetcode)