leetcode.208. Implement Trie (Prefix Tree) 字典树

来源:互联网 发布:在淘宝网如何注册网店 编辑:程序博客网 时间:2024/05/22 01:39

Implement a trie with insert, search, and startsWith methods.

Note:
You may assume that all inputs are consist of lowercase letters a-z.

class TrieNode {public:    // Initialize your data structure here.     bool isEnd;      TrieNode *children[26];      TrieNode() : isEnd(false)      {          for (int i = 0; i < 26; i++)          {              children[i] = NULL;          }      }  };class Trie {public:    Trie() {        root = new TrieNode();    }    // Inserts a word into the trie.    void insert(string word) {        TrieNode *cur = root;          for (int i = 0; i < word.length(); i++)          {              int index = word[i] - 'a';              if (cur->children[index] == NULL)              {                  cur->children[index] = new TrieNode();              }                cur = cur->children[index];          }            cur->isEnd = true;       }    // Returns if the word is in the trie.    bool search(string word) {        int n = word.length();          return search(word, n, 0, root);             }     bool search(string &word, int n, int pos, TrieNode *cur)      {          if (cur == NULL)  return false;                    if (pos == n)   return cur->isEnd;                    int index = word[pos] - 'a';          if (cur->children[index])          {              return search(word, n, pos+1, cur->children[index]);          }          return false;      }      // Returns if there is any word in the trie    // that starts with the given prefix.    bool startsWith(string prefix) {         TrieNode *cur = root;         for(int i = 0;i<prefix.size();i++)         {             int index = prefix[i] - 'a';               if (cur->children[index] == NULL)                  return false;               cur = cur->children[index];          }                  return true;    }private:    TrieNode* root;};// Your Trie object will be instantiated and called as such:// Trie trie;// trie.insert("somestring");// trie.search("key");


0 0
原创粉丝点击