[LeetCode] Implement Trie (Prefix Tree)

Implement a trie with insertsearch, and startsWith methods.

Note:
You may assume that all inputs are consist of lowercase letters a-z.

实现字典树,没啥好说的。

 1 class TrieNode {
 2 public:
 3     // Initialize your data structure here.
 4     TrieNode *ch[26];
 5     bool isKey;
 6     TrieNode() : isKey(false) {
 7         for (auto &a : ch) a = NULL;
 8     }
 9 };
10 
11 class Trie {
12 public:
13     Trie() {
14         root = new TrieNode();
15     }
16 
17     // Inserts a word into the trie.
18     void insert(string s) {
19         TrieNode *p = root;
20         for (auto &a : s) {
21             int i = a - 'a';
22             if (p->ch[i] == NULL) p->ch[i] = new TrieNode();
23             p = p->ch[i];
24         }
25         p->isKey = true;
26     }
27 
28     // Returns if the word is in the trie.
29     bool search(string key) {
30         TrieNode *p = root;
31         for (auto &a : key) {
32             int i = a - 'a';
33             if (p->ch[i] == NULL) return false;
34             p = p->ch[i];
35         }
36         return p->isKey;
37     }
38 
39     // Returns if there is any word in the trie
40     // that starts with the given prefix.
41     bool startsWith(string prefix) {
42         TrieNode *p = root;
43         for (auto &a : prefix) {
44             int i = a - 'a';
45             if (p->ch[i] == NULL) return false;
46             p = p->ch[i];
47         }
48         return true;
49     }
50 
51 private:
52     TrieNode* root;
53 };
54 
55 // Your Trie object will be instantiated and called as such:
56 // Trie trie;
57 // trie.insert("somestring");
58 // trie.search("key");

 

你可能感兴趣的:(LeetCode)