208. Implement Trie (Prefix Tree) 前綴樹的實現

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:
    bool isKey;
    TrieNode* children[26];
    TrieNode(): isKey(false) {
        memset(children, NULL, sizeof(TrieNode*) * 26); 
    }
};
它的優點是:利用字符串的公共前綴來減少查詢時間,最大限度地減少無謂的字符串比較,查詢效率比哈希樹高。


iskey是用來標記是否從根節點(root)到當前節點node所組成的字符串是否是一個關鍵字(一整個單詞是否被添加)
在這個問題中,只考慮小寫字符,因此每個節點最多有26的子節點;將其存儲在TrieNode *children[26];其中數組對應的字符是  i+'a'

class TrieNode {
public:
  // Initialize your data structure here.
  bool iskey;
  TrieNode *children[26];
  TrieNode():iskey(false) {
      memset(children, NULL, sizeof(TrieNode*)*26);
  }
};

class Trie {
public:

  Trie() {
      root = new TrieNode();
  }

  // Inserts a word into the trie.
  void insert(string word) {
      TrieNode *p=root;
      for(int i=0;i<word.size();i++) {
          if(p->children[word[i]-'a']==NULL){
              p->children[word[i]-'a']=new TrieNode();
          }
          p=p->children[word[i]-'a'];
      }
      p->iskey=true;
  }

  // Returns if the word is in the trie.
  bool search(string word) {
      TrieNode *p=root;
      for(int i=0;i<word.size()&&p!=NULL;i++) {
          p=p->children[word[i]-'a'];
      }
      return p&&p->iskey;
  }

  // Returns if there is any word in the trie
  // that starts with the given prefix.
  bool startsWith(string prefix) {
      TrieNode *p=root;
      for(int i=0;i<prefix.size()&&p!=NULL;i++) {
          p=p->children[prefix[i]-'a'];
      }
      return p;
  }

private:
  TrieNode* root;
};

// Your Trie object will be instantiated and called as such:
// Trie trie;
// trie.insert("somestring");
// trie.search("key");


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章