leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0211.cpp (976B)


      1 class WordDictionary {
      2     vector<WordDictionary *> children;
      3     bool isEndOfWord = false;
      4     ;
      5 
      6   public:
      7     WordDictionary() : children(vector<WordDictionary *>(26, nullptr)) {}
      8 
      9     void addWord(string word) {
     10         WordDictionary *crnt = this;
     11         for (char c : word) {
     12             if (crnt->children[c - 'a'] == nullptr) crnt->children[c - 'a'] = new WordDictionary();
     13             crnt = crnt->children[c - 'a'];
     14         }
     15         crnt->isEndOfWord = true;
     16     }
     17 
     18     bool search(string word) {
     19         WordDictionary *crnt = this;
     20         for (int i = 0; i < word.length(); ++i) {
     21             if (word[i] == '.') {
     22                 for (auto c : crnt->children)
     23                     if (c && c->search(word.substr(i + 1))) return true;
     24                 return false;
     25             }
     26             if (crnt->children[word[i] - 'a'] == nullptr) return false;
     27             crnt = crnt->children[word[i] - 'a'];
     28         }
     29         return crnt && crnt->isEndOfWord;
     30     }
     31 };