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");


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值