leetcodeSolution to some Leetcode problems written in C++ |
git clone git://git.dimitrijedobrota.com/leetcode.git |
Log | Files | Refs | README | LICENSE |
0211.cpp (976B)
0 class WordDictionary { 1 vector<WordDictionary *> children; 2 bool isEndOfWord = false; 3 ; 4 5 public: 6 WordDictionary() : children(vector<WordDictionary *>(26, nullptr)) {} 7 8 void addWord(string word) { 9 WordDictionary *crnt = this; 10 for (char c : word) { 11 if (crnt->children[c - 'a'] == nullptr) crnt->children[c - 'a'] = new WordDictionary(); 12 crnt = crnt->children[c - 'a']; 13 } 14 crnt->isEndOfWord = true; 15 } 16 17 bool search(string word) { 18 WordDictionary *crnt = this; 19 for (int i = 0; i < word.length(); ++i) { 20 if (word[i] == '.') { 21 for (auto c : crnt->children) 22 if (c && c->search(word.substr(i + 1))) return true; 23 return false; 24 } 25 if (crnt->children[word[i] - 'a'] == nullptr) return false; 26 crnt = crnt->children[word[i] - 'a']; 27 } 28 return crnt && crnt->isEndOfWord; 29 } 30 };