Implement Trie
Implement a trie with insert, search, and startsWith methods.
insert(“lintcode”)
search(“code”) // return false
startsWith(“lint”) // return true
startsWith(“linterror”) // return false
insert(“linterror”)
search(“lintcode) // return true
startsWith(“linterror”) // return true
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
|
class TrieNode { public: TrieNode() { for(int i = 0; i < 26; i++) next[i] = NULL; isString = false; } TrieNode *next[26]; bool isString; }; class Trie { public: Trie() { root = new TrieNode(); } void (string word) { TrieNode *p = root; for(int i = 0; i < word.size(); i++){ if(p->next[word[i]-'a'] == NULL){ p->next[word[i]-'a'] = new TrieNode(); } p = p->next[word[i]-'a']; } p->isString = true; } bool search(string word) { TrieNode *p = root; for(int i = 0; i < word.size(); i++){ if(p == NULL) return false; p = p->next[word[i]-'a']; } if(p == NULL || p->isString == false) return false; return true; } bool startsWith(string prefix) { TrieNode *p = root; for(int i = 0; i < prefix.size(); i++) { p = p->next[prefix[i]-'a']; if(p == NULL) return false; } return true; } private: TrieNode* root; };
|
Add and Search Word
Design a data structure that supports the following two operations: addWord(word) and search(word)
search(word) can search a literal word or a regular expression string containing only letters a-z or ..
A . means it can represent any one letter.
addWord(“bad”)
addWord(“dad”)
addWord(“mad”)
search(“pad”) // return false
search(“bad”) // return true
search(“.ad”) // return true
search(“b..”) // return true
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
|
class TrieNode { public: bool isString; TrieNode *next[26]; TrieNode () { for (int i = 0; i < 26; i++) next[i] = NULL; isString = false; } }; class WordDictionary { public: WordDictionary () { root = new TrieNode(); } void addWord(string word) { TrieNode *p = root; for (char c : word) { if (!p->next[c-'a']) { p->next[c-'a'] = new TrieNode(); } p = p->next[c-'a']; } p->isString = true; } bool search(string word) { TrieNode *p = root; bool res = helper(word, 0, p); return res; } bool helper(string word, int pos, TrieNode *p) { if (!p) return false; if (pos >= word.size()) { if (p->isString) return true; else return false; } if (word[pos] != '.') return helper(word, pos+1, p->next[word[pos]-'a']); else { bool res = false; for (int j = 0; j < 26; j++) { if (p->next[j] != NULL) { res = res || helper(word, pos+1, p->next[j]); } } return res; } } private: TrieNode *root; };
|
近期评论