LeetCode 208 Implement Trie (Prefix Tree)

标签: 设计数据结构 LeetCode 发布于:2022-02-10 18:43:16 编辑于:2022-02-10 18:43:16 浏览量:1051

概述

https://leetcode.com/problems/implement-trie-prefix-tree/

基于多叉树的前缀树实现

注意指针数组要初始化,否则:member access within misaligned address

class Trie {
public:
    class Node {
    public: 
        Node* children[26];
        bool end = false;
        Node() : children() {}
    };
    
    Node* root;
    
    Trie() {
        root = new Node;
    }
    
    void insert(string word) {
        auto node = root;
        for (auto c : word) {
            if (!node->children[c - 'a']) {
                node->children[c - 'a'] = new Node;
            }
            node = node->children[c - 'a'];
        }
        node->end = true;
    }
    
    bool search(string word) {
        auto node = root;
        for (auto c : word) {
            if (node->children[c - 'a']) {
                node = node->children[c - 'a'];
            } else {
                cout << endl;
                return false;
            }
        }
        return node->end;
    }
    
    bool startsWith(string prefix) {
        auto node = root;
        for (auto c : prefix) {
            if (node->children[c - 'a']) {
                node = node->children[c - 'a'];
            } else {
                return false;
            }
        }
        return true;
    }
};

未经允许,禁止转载,本文源站链接:https://iamazing.cn/