题目链接: https://leetcode.com/problems/add-and-search-word-data-structure-design/
Design a data structure that supports the following two operations:
void addWord(word) bool search(word)
search(word) can search a literal word or a regular expression string containing only letters a-z
or .
. A .
means it can represent any one letter.
For example:
addWord("bad") addWord("dad") addWord("mad") search("pad") -> false search("bad") -> true search(".ad") -> true search("b..") -> true
Note:
You may assume that all words are consist of lowercase letters a-z
.
思路: 实现一个字典树, 完成添加和查找的操作.
其原理是每个结点有26个孩子结点, 一个结点的26孩子结点初始默认为NULL. 如果我们要添加一个单词, 那么这个单词会从根节点往下一层层生长, 当到单词结尾的时候我们在最后的结点做个标记,代表从根节点到这个结点路径是一个单词.
在添加单词的时候因为公共前缀的单词会共用一些路径, 因此字典树可以极大的节约内存.
代码如下:
class WordDictionary { public: typedef struct Trie { vector<Trie*> child; bool isWord; Trie(): child(vector<Trie*>(26, NULL)), isWord(false){} }Trie; WordDictionary():root(new Trie()){} // Adds a word into the data structure. void addWord(string word) { Trie* tem = root; for(auto ch: word) { if(tem->child[ch - 'a'] == NULL)//如果ch不在树上, 则将其添加到字典树中 tem->child[ch - 'a'] = new Trie(); tem = tem->child[ch - 'a']; } tem->isWord = true;//在路径的最后标记到当前结点的路径构成一个单词 } bool DFS(string str, Trie* node) { if(node == NULL) return false; if(str.size() ==0) return node->isWord;//如果字符串遍历完了,则看到当前结点是否可以构成一个单词 if(str[0] != '.')//不是.则是一对一匹配 { if(node->child[str[0]-'a'] == NULL) return false; return DFS(str.substr(1), node->child[str[0]-'a']); } for(int i = 0; i < 26; i++)//如果是.,则需要遍历所有的可能性 if(DFS(str.substr(1), node->child[i]) == true) return true; return false; } // 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) { Trie* tem = root; return DFS(word, tem); } private: Trie* root; }; // Your WordDictionary object will be instantiated and called as such: // WordDictionary wordDictionary; // wordDictionary.addWord("word"); // wordDictionary.search("pattern");参考: https://leetcode.com/discuss/45435/c-using-trie-and-dfs-for-search-easy-understand-solution