Leetcode171: Implement Trie (Prefix Tree)

来源:互联网 发布:web编程语言 编辑:程序博客网 时间:2024/06/06 12:20

Implement a trie with insertsearch, and startsWith methods.

Trie树又被称为字典树、前缀树,是一种用于快速检索的多叉树。Tried树可以利用字符串的公共前缀来节省存储空间。

但如果系统存在大量没有公共前缀的字符串,相应的Trie树将非常消耗内存。

Trie树的基本性质如下:

  • 根节点不包括字符,除根节点外每个节点包括一个支付。
  • 从根节点到某一节点,路径上经过的字符连接起来,即为对应的字符串。
  • 每个节点的所有子节点包含的字符串各不相同。

本题中的Trie树可以简单实现如下:

Trie树节点数据结构定义如下:

  1. val表示该节点对应的字符
  2. 子节点简单用一个数组表示,这样实现比较简单,但比较耗费内存
  3. isWord标记从根节点到该节点是否表示一个单词,还是另一单词的前缀。
class TrieNode {public:    // Initialize your data structure here.    char var;      bool isWord;      TrieNode* children[26];      // Initialize your data structure here.      TrieNode() {          var = 0;          isWord = false;          memset(children, 0x0, sizeof(TreeNode*)*26);        }      TrieNode(char c){          var = c;          isWord = false;          memset(children, 0x0, sizeof(TreeNode*)*26);      }  };class Trie {public:    Trie() {        root = new TrieNode();    }    // Inserts a word into the trie.    void insert(string word) {        TrieNode* pNode = root;          if (word.length() <= 0)          {              return;          }          for (int i= 0; i<word.length(); i++)          {              char c= word[i];              if (pNode->children[c-'a'] == 0)              {                  TrieNode *pNew = new TrieNode(c);                  pNode->children[c-'a'] = pNew;              }              pNode = pNode->children[c-'a'];          }          pNode->isWord = true;    }    // Returns if the word is in the trie.    bool search(string word) {        TrieNode *pNode = root;          if (word.length() <= 0)              return true;          for (int i =0; i<word.length(); i++)          {              char c = word[i];              pNode = pNode->children[c-'a'];              if (pNode == NULL)                  return false;          }          return pNode->isWord;     }    // Returns if there is any word in the trie    // that starts with the given prefix.    bool startsWith(string prefix) {        TrieNode *pNode = root;          if (prefix.length()<=0)              return true;          for (int i=0; i<prefix.length(); i++)          {              char c = prefix[i];              pNode = pNode->children[c-'a'];              if (pNode == NULL)                  return false;          }          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
原创粉丝点击