zoukankan      html  css  js  c++  java
  • LeetCode 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.

     1 class TrieNode{
     2 public:
     3     TrieNode():isWord(false)
     4     {
     5         memset(next,0,sizeof(TrieNode*)*26);
     6     }
     7     TrieNode(char _c):c(_c),isWord(false)
     8     {
     9         memset(next,0,sizeof(TreeNode*)*26);
    10     }
    11     TrieNode* next[26];
    12     char c;
    13     bool isWord;
    14 };
    15 
    16 class Trie {
    17 public:
    18     /** Initialize your data structure here. */
    19     Trie() {
    20         root=new TrieNode();
    21     }
    22     
    23     /** Inserts a word into the trie. */
    24     void insert(string word) {
    25         TrieNode* p=root;
    26         int id;
    27         for(char c:word)
    28         {
    29             id=c-'a';
    30             if(p->next[id]==nullptr)
    31                 p->next[id]=new TrieNode(c);
    32             p=p->next[id];
    33         }
    34         p->isWord=true;
    35     }
    36     
    37     /** Returns if the word is in the trie. */
    38     bool search(string word) {
    39         TrieNode* p=root;
    40         int id;
    41         for(char c:word)
    42         {
    43             id=c-'a';
    44             if(p->next[id]==nullptr)
    45                 return false;
    46             p=p->next[id];
    47         }
    48         return p->isWord;
    49     }
    50     
    51     /** Returns if there is any word in the trie that starts with the given prefix. */
    52     bool startsWith(string prefix) {
    53         TrieNode* p=root;
    54         int id;
    55         for(char c:prefix)
    56         {
    57             id=c-'a';
    58             if(p->next[id]==nullptr)
    59                 return false;
    60             p=p->next[id];
    61         }
    62         return true;
    63     }
    64 private:
    65     TrieNode* root;
    66 };
    67 
    68 /**
    69  * Your Trie object will be instantiated and called as such:
    70  * Trie obj = new Trie();
    71  * obj.insert(word);
    72  * bool param_2 = obj.search(word);
    73  * bool param_3 = obj.startsWith(prefix);
    74  */
  • 相关阅读:
    hlgoj 1766 Cubing
    Reverse Linked List
    String to Integer
    Bitwise AND of Numbers Range
    Best Time to Buy and Sell Stock III
    First Missing Positive
    Permutation Sequence
    Next Permutation
    Gray Code
    Number of Islands
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8574832.html
Copyright © 2011-2022 走看看