Implement a trie with insert
, search
, 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");
时间: 2024-10-13 14:15:25