Implement a trie with insert
, search
, and startsWith
methods.
Note:
You may assume that all inputs are consist of lowercase letters a-z
.
思路:
构建一个简单的字典树,要求实现插入、查找、查找前缀三个操作。这里使用map实现对子树的构建(一方面方便查找,另一方面是懒 - -!),但是效率并不是太高,LeetCode上提交后跑了147ms,不是很理想,不过不影响对字典树这种树形结构的理解。
1 class TrieNode { 2 public: 3 // Initialize your data structure here. 4 TrieNode(char c):ch(c), isEnd(false){} 5 6 map<char, TrieNode *> childNode; 7 8 char ch; 9 bool isEnd; 10 }; 11 12 class Trie { 13 public: 14 Trie() { 15 root = new TrieNode(‘#‘); 16 } 17 18 // Inserts a word into the trie. 19 void insert(string s) { 20 21 TrieNode *t = root; 22 23 //从root遍历待插入字符串,若c存在则继续向下遍历,反之则新建一个分支 24 for(int i = 0; i < s.length(); i++) 25 { 26 char c = s[i]; 27 28 map<char, TrieNode*>::iterator it = t->childNode.find(c); 29 if(it == t->childNode.end()) 30 { 31 TrieNode *newNode = new TrieNode(c); 32 t->childNode.insert(make_pair(c, newNode)); 33 t = newNode; 34 } 35 else 36 { 37 t = t->childNode[c]; 38 } 39 } 40 t->isEnd = true; 41 } 42 43 // Returns if the word is in the trie. 44 bool search(string key) { 45 TrieNode *s = root; 46 47 //从root遍历待查找字符串,若c存在则向下遍历,反之则不存在 48 for(int i = 0; i < key.length(); i++) 49 { 50 char c = key[i]; 51 52 map<char, TrieNode*>::iterator it = s->childNode.find(c); 53 if(it == s->childNode.end()) 54 return false; 55 else 56 s = s->childNode[c]; 57 } 58 //返回最后一个结点的状态,判断是否为一个word 59 return s->isEnd; 60 } 61 62 // Returns if there is any word in the trie 63 // that starts with the given prefix. 64 bool startsWith(string prefix) { 65 TrieNode *s = root; 66 67 //与search一致 68 for(int i = 0; i < prefix.length(); i++) 69 { 70 char c = prefix[i]; 71 72 map<char, TrieNode*>::iterator it = s->childNode.find(c); 73 74 if(it == s->childNode.end()) 75 return false; 76 else 77 s = s->childNode[c]; 78 } 79 //只要找到即返回true 80 return true; 81 } 82 83 private: 84 TrieNode* root; 85 };
时间: 2024-10-16 12:15:24