天天看點

LeetCode-208. Implement Trie (Prefix Tree)

Implement a trie with ​

​insert​

​​, ​

​search​

​​, and ​

​startsWith​

​ methods.

Example:

Trie trie = new Trie();

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

Note:

  • You may assume that all inputs are consist of lowercase letters​

    ​a-z​

    ​.
  • All inputs are guaranteed to be non-empty strings.

題解:

class Trie {
    struct trieTree {
        trieTree* child[26];
        bool isWord;
        bool hasPrefix;
        trieTree() {
            for (int i = 0; i < 26; i++) {
                child[i] = NULL;
            }
            isWord = false;
            hasPrefix = false;
        }
    };
    trieTree *root;
public:
    /** Initialize your data structure here. */
    Trie() {
        root = new trieTree();
    }
    
    /** Inserts a word into the trie. */
    void insert(string word) {
        trieTree *t = root;
        for (int i = 0; i < word.size(); i++) {
            if (t->child[word[i]- 'a'] == NULL) {
                t->child[word[i] - 'a'] = new trieTree();
                t->hasPrefix = true;
            }
            t = t->child[word[i] - 'a'];
        }
        t->isWord = true;
        t->hasPrefix = true;
    }
    
    /** Returns if the word is in the trie. */
    bool search(string word) {
        trieTree *t = root;
        for (int i = 0; i < word.size(); i++) {
            if (t->child[word[i]- 'a'] == NULL) {
                return false;
            }
            t = t->child[word[i] - 'a'];
        }
        return t->isWord;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    bool startsWith(string prefix) {
        trieTree *t = root;
        for (int i = 0; i < prefix.size(); i++) {
            if (t->child[prefix[i]- 'a'] == NULL) {
                return false;
            }
            t = t->child[prefix[i] - 'a'];
        }
        return t->hasPrefix;
    }
};      
i++