442. Implement Trie (Prefix Tree)

class trieNode{
public:    
    trieNode *child[26]; 
    bool isValid; 
    trieNode(){
      for(int i = 0; i < 26; i++){
          this->child[i] = NULL; 
      }
      this->isValid = false; 
    }
}; 
class Trie {
public:
    trieNode *root; 
    Trie() {
        // do intialization if necessary
        root = new trieNode(); 
    }

    /*
     * @param word: a word
     * @return: nothing
     */
    void insert(string &word) {
        // write your code here
        int len = word.size(); 
        trieNode *root1 = root; 
        for(int i = 0; i < len; i++){
            if(root1->child[word[i] - 'a'] == NULL){
                root1->child[word[i] - 'a'] = new trieNode(); 
            }
            root1 = root1->child[word[i] - 'a']; 
        }
        root1->isValid = true; 
        return; 
    }

    /*
     * @param word: A string
     * @return: if the word is in the trie.
     */
    bool search(string &word) {
        // write your code here
        int len = word.size(); 
        trieNode *root1 = root; 
        for(int i = 0; i < len; i++){
            int idx = word[i] - 'a'; 
            if(root1->child[idx] == NULL){
                return false; 
            }
            root1 = root1->child[idx]; 
        }
        return root1->isValid; 
    }

    /*
     * @param prefix: A string
     * @return: if there is any word in the trie that starts with the given prefix.
     */
    bool startsWith(string &prefix) {
        // write your code here
        int len = prefix.size();
        trieNode *root1 = root; 
        for(int i = 0; i < len; i++){
            int idx = prefix[i] - 'a'; 
            if(root1->child[idx] == NULL){
                return false; 
            }
            root1 = root1->child[idx]; 
        }
        return true; 
    }
};

    Comments

    Popular posts from this blog

    算法的比较