设计一个支持如下两种操做的数据结构:正则表达式
void addWord(word) bool search(word)数据结构
search(word) 能够搜索文字或正则表达式字符串,字符串只包含字母 . 或 a-z 。 . 能够表示任何一个字母。设计
示例:code
addWord("bad") addWord("dad") addWord("mad") search("pad") -> false search("bad") -> true search(".ad") -> true search("b..") -> true字符串
说明:string
你能够假设全部单词都是由小写字母 a-z 组成的。it
典型的字典树,前缀树的用法io
class WordDictionary { public: struct TrieNode { TrieNode(): isword(false), children(26, nullptr){} ~TrieNode() { for(TrieNode* child : children) { if(child) delete child; } } bool isword; vector<TrieNode*> children; }; TrieNode* root; /** Initialize your data structure here. */ WordDictionary() : root(new TrieNode()){ } /** Adds a word into the data structure. */ void addWord(string word) { TrieNode *p = root; for(char c : word) { if(p ->children[c - 'a'] == nullptr) { p ->children[c - 'a'] = new TrieNode(); } p = p ->children[c - 'a']; } p ->isword = 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) const{ TrieNode *p = root; for(int i = 0; i < word.size(); i++) { if(word[i] == '.') { for(int j = 0; j < 26; j++) { if(p ->children[j]) { if(Find(string(word.begin() + i + 1, word.end()), p ->children[j])) return true; } } return false; } else { p = p ->children[word[i] - 'a']; if(p == nullptr) return false; } } if(p ->isword) return true; return false; } const bool Find(string word, TrieNode* p) const { for(int i = 0; i < word.size(); i++) { if(word[i] == '.') { for(int j = 0; j < 26; j++) { if(p ->children[j]) { if(Find(string(word.begin() + i + 1, word.end()), p ->children[j])) return true; } } return false; } else { p = p ->children[word[i] - 'a']; if(p == nullptr) return false; } } if(p ->isword) return true; return false; } };