Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class TrieNode {
- public:
- bool end;
- TrieNode* children[26];
- TrieNode() {
- end = false;
- for(int i=0; i<26; i++)
- children[i] = NULL;
- }
- };
- class WordDictionary {
- public:
- /** Initialize your data structure here. */
- WordDictionary() {
- }
- /** Adds a word into the data structure. */
- void addWord(string word) {
- TrieNode* node = root;
- for(char c : word) {
- c -= 'a';
- if(!node->children[c]) {
- node->children[c] = new TrieNode();
- }
- node = node->children[c];
- }
- node->end = true;
- }
- /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
- bool search(string word) {
- return search(word.c_str(), root);
- }
- private:
- TrieNode* root = new TrieNode();
- bool search(const char* word, TrieNode* node) {
- for(int i = 0; word[i] && node; i++) {
- if(word[i] != '.') {
- node = node->children[word[i] - 'a'];
- } else {
- TrieNode* tmp = node;
- for(int j = 0; j < 26; j++) {
- node = tmp->children[j];
- if(search(word + i + 1, node)) {
- return true;
- }
- }
- }
- }
- return node && node->end;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement