标签:
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
.
采用trie树,参考:http://blog.csdn.net/u012243115/article/details/47252213。
查找过程中,如果遇到字符为‘.’ ,则对子节点进行深度优先遍历。
class Trie { public: bool isWord; Trie *next[26]; Trie() { isWord = false; memset(next , 0 , sizeof(next)); } }; class WordDictionary { public: WordDictionary() { root = new Trie(); } // Adds a word into the data structure. void addWord(string word) { Trie *p = root; int len = word.size(); for(int i = 0 ; i < len ; i++) { if(p->next[word[i] - 'a'] == NULL) p->next[word[i] - 'a'] = new Trie(); p = p->next[word[i] - '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) { return DFS(word , root); } bool DFS(string word , Trie *root) { Trie *p = root; int len = word.size(); bool result = false; for(int i = 0 ; i < len && p ; i++) { if(word[i] != '.') p = p->next[word[i] - 'a']; else { Trie *tmp = p; //临时把p保存下来,下面对p的next结点使用深搜 for(int j = 0 ; j < 26 ; j++) { p = tmp->next[j]; if(p) result = DFS(word.substr(i+1) , p); //对i后面的子串递归调用 if(result) return result; } } } return p && p->isWord; } private: Trie *root; }; // Your WordDictionary object will be instantiated and called as such: // WordDictionary wordDictionary; // wordDictionary.addWord("word"); // wordDictionary.search("pattern");
版权声明:转载请注明出处。
LeetCode OJ 之 Add and Search Word - Data structure design (Trie数据结构设计)
标签:
原文地址:http://blog.csdn.net/u012243115/article/details/47253273