标签:lap square air efi toc font you add dict
【208】Implement Trie (Prefix Tree) (2018年11月27日)
实现基本的 trie 树,包括 insert, search, startWith 操作等 api。
题解:《程序员代码面试指南》chp5, 最后一题。 里面讲了怎么实现。这个就看代码吧。没啥好说的了。
1 class Trie { 2 public: 3 /** Initialize your data structure here. */ 4 Trie() { 5 root = new TrieNode(); 6 } 7 8 /** Inserts a word into the trie. */ 9 void insert(string word) { 10 if (word.empty()) {return;} 11 const int n = word.size(); 12 TrieNode* node = root; 13 int index = 0; 14 for (int i = 0; i < n; ++i) { 15 index = word[i] - ‘a‘; 16 if (node->mp.find(index) == node->mp.end()) { 17 node->mp[index] = new TrieNode(); 18 } 19 node = node->mp[index]; 20 node->path++; 21 } 22 node->end++; 23 } 24 25 /** Returns if the word is in the trie. */ 26 bool search(string word) { 27 if (word.empty()) {return false;} 28 TrieNode* node = root; 29 const int n = word.size(); 30 int index = 0; 31 for (int i = 0; i < n; ++i) { 32 index = word[i] - ‘a‘; 33 if (node->mp.find(index) == node->mp.end()) { 34 return false; 35 } 36 node = node->mp[index]; 37 if (node->path == 0) { 38 return false; 39 } 40 } 41 return node->end >= 1; 42 } 43 44 /** Returns if there is any word in the trie that starts with the given prefix. */ 45 bool startsWith(string prefix) { 46 if (prefix.empty()) {return false;} 47 const int n = prefix.size(); 48 TrieNode* node = root; 49 int index = 0; 50 for (int i = 0; i < n; ++i) { 51 index = prefix[i] - ‘a‘; 52 if (node->mp.find(index) == node->mp.end()) { 53 return false; 54 } 55 node = node->mp[index]; 56 if (node->path == 0) { 57 return false; 58 } 59 } 60 return node->path >= 1; 61 } 62 63 //define trie node 64 struct TrieNode{ 65 int path; //代表多少个单词共用这个结点 66 int end; //代表多少个单词以这个结点结尾 67 map<int, TrieNode*> mp; 68 TrieNode() { 69 path = 0, end = 0; 70 } 71 }; 72 TrieNode* root; 73 }; 74 75 /** 76 * Your Trie object will be instantiated and called as such: 77 * Trie obj = new Trie(); 78 * obj.insert(word); 79 * bool param_2 = obj.search(word); 80 * bool param_3 = obj.startsWith(prefix); 81 */
【211】Add and Search Word - Data structure design
【212】Word Search II
【336】Palindrome Pairs
【421】Maximum XOR of Two Numbers in an Array
【425】Word Squares
【472】Concatenated Words
【642】Design Search Autocomplete System
【648】Replace Words
【676】Implement Magic Dictionary
【677】Map Sum Pairs
【692】Top K Frequent Words
【720】Longest Word in Dictionary
【745】Prefix and Suffix Search
标签:lap square air efi toc font you add dict
原文地址:https://www.cnblogs.com/zhangwanying/p/9964323.html