문제

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

걸린 시간

-

풀이

C++

class Trie {
public:
    Trie* children[26];
    bool terminal;
    /* char to int */
    int toNumber(char ch) { return ch-'a'; }
    /** Initialize your data structure here. */
    Trie() {
        terminal = false;
        memset(children, 0, sizeof(children));
    }

    /** Inserts a word into the trie. */
    void insert(string word) {
        if(word[0] == 0) terminal = true;
        else{
            int next = toNumber(word[0]);
            if(children[next] == NULL)
                children[next] = new Trie();
            children[next]->insert(word.c_str()+1);
        }
    }

    /** Returns if the word is in the trie. */
    bool search(string word) {
        if(word[0] == 0) return this->terminal;
        int next = toNumber(word[0]);
        if(children[next] == NULL) return false;
        return children[next]->search(word.c_str()+1);
    }

    /** Returns if there is any word in the trie that starts with the given prefix. */
    bool startsWith(string prefix) {
        if(prefix[0] == 0) return true;
        int next = toNumber(prefix[0]);
        if(children[next] == NULL) return false;
        return children[next]->startsWith(prefix.c_str()+1);
    }
};

/**
 * 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);
 */

기본적인 트라이 자료구조 구현 문제.

댓글