Solution:
May use the prefix trie data structure. Then need DSF for the word searching. As long as there is one path is right, return true; otherwise, return false.
Code:
class WordDictionary { public: struct TrieNode{ bool end; vector<TrieNode*> children; TrieNode(): end(false), children(26, NULL) {} }; WordDictionary(){//constructor; root = new TrieNode(); } // Adds a word into the data structure. void addWord(string word) { TrieNode *t = root; for(auto a:word){ if(!t->children[a-'a']) t->children[a-'a'] = new TrieNode(); t = t->children[a-'a']; } t->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 swDSF(word, root, 0); } bool swDSF(string w, TrieNode* r, int i){ if(i == w.size()) return r->end; if(w[i] == '.'){ for(auto a:r->children){ if(a && swDSF(w, a, i+1)) return true; } return false; } return r->children[w[i]-'a'] && swDSF(w, r->children[w[i]-'a'], i+1); } private: TrieNode *root; }; // Your WordDictionary object will be instantiated and called as such: // WordDictionary wordDictionary; // wordDictionary.addWord("word"); // wordDictionary.search("pattern");
No comments :
Post a Comment