• LeetCode OJ:Implement Trie (Prefix Tree)(实现一个字典树(前缀树))


    Implement a trie with insertsearch, and startsWith methods.

    实现字典树,前面好像有道题做过类似的东西,代码如下:

     1 class TrieNode {
     2 public:
     3     // Initialize your data structure here.
     4     TrieNode():isLeaf(false)
     5     {
     6         for(auto & t : dic){
     7             t = NULL;
     8         }
     9     }
    10     TrieNode * dic[26];
    11     bool isLeaf;
    12 };
    13 
    14 class Trie {
    15 public:
    16     Trie() {
    17         root = new TrieNode();
    18     }
    19 
    20     // Inserts a word into the trie.
    21     void insert(string word) {
    22         TrieNode * p = root;
    23         for(int i = 0; i < word.size(); ++i){
    24             int index = word[i] - 'a';
    25             if(p->dic[index] == NULL)
    26                 p->dic[index] = new TrieNode();
    27             p = p->dic[index];
    28         }
    29         p->isLeaf = true;
    30     }
    31 
    32     // Returns if the word is in the trie.
    33     bool search(string word) {
    34         TrieNode * p = root;
    35         for(int i = 0; i < word.size(); ++i){
    36             int index = word[i] - 'a';
    37             if(p->dic[index] == NULL)
    38                 return false;
    39             p = p->dic[index];
    40         }
    41         return p->isLeaf;
    42     }
    43 
    44     // Returns if there is any word in the trie
    45     // that starts with the given prefix.
    46     bool startsWith(string prefix) {
    47         TrieNode * p = root;
    48         for(int i = 0; i < prefix.size(); ++i){
    49             int index = prefix[i] - 'a';
    50             if(p->dic[index] == NULL)
    51                 return false;
    52             p = p->dic[index];
    53         }
    54         return true;
    55     }
    56 
    57 private:
    58     TrieNode* root;
    59 };
    60 
    61 // Your Trie object will be instantiated and called as such:
    62 // Trie trie;
    63 // trie.insert("somestring");
    64 // trie.search("key");
  • 相关阅读:
    5. support vector machine
    机器学习实战(二)决策树
    机器学习实战(一)kNN
    深度学习笔记(无)VGG14
    深度学习笔记(一)线性分类器(基础知识)
    Eclipse代码风格
    windows安装java环境
    linux matlab2013b 安装教程
    小白Linux入门 五
    机器学习 0
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/5015300.html
Copyright © 2020-2023  润新知