/* * @lc app=leetcode id=211 lang=cpp * * [211] Add and Search Word - Data structure design */// @lc code=startclassWordDictionary {public:classTrieNode {public:char val;bool end; unordered_map<char, TrieNode*> children;TrieNode(char v,bool e):val(v),end(e) {} }; TrieNode *root; /** Initialize your data structure here. */WordDictionary() { root =newTrieNode('-',false); } /** Adds a word into the data structure. */voidaddWord(string word) { TrieNode *cur = root;for (int i =0; i <word.length(); ++i) {constauto c =word[i];if (!cur->children.count(c)) cur->children[c] =newTrieNode(c,false); cur =cur->children[c];if (i ==word.length() -1) cur->end =true; } }booldfs(TrieNode*cur,string&word,int pos) {for (; pos <word.length(); ++pos) {constauto c =word[pos];if (c =='.') {for (constauto&p :cur->children) {if (dfs(p.second, word, pos +1)) {returntrue; } }returnfalse; } else {if (!cur->children.count(c)) returnfalse; cur =cur->children[c]; } }returncur->end; } /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
boolsearch(string word) {returndfs(root, word,0); }};/** * Your WordDictionary object will be instantiated and called as such: * WordDictionary* obj = new WordDictionary(); * obj->addWord(word); * bool param_2 = obj->search(word); */// @lc code=end
class WordDictionary {
class TrieNode {
TrieNode[] children = new TrieNode[26];
boolean word = false;
}
TrieNode root;
/** Initialize your data structure here. */
public WordDictionary() {
root = new TrieNode();
}
/** Adds a word into the data structure. */
public void addWord(String word) {
TrieNode node = root;
for (int i = 0; i < word.length(); i++) {
int index = word.charAt(i) - 'a';
if (node.children[index] == null) {
node.children[index] = new TrieNode();
}
node = node.children[index];
}
node.word = true;
}
private boolean search(String word, int start, TrieNode node) {
for (int i = start; i < word.length(); i++) {
if (word.charAt(i) == '.') {
for (int j = 0; j < 26; j++) {
if (node.children[j] != null && search(word, i + 1, node.children[j])) {
return true;
}
}
return false;
} else {
int index = word.charAt(i) - 'a';
if (node.children[index] == null) {
return false;
}
node = node.children[index];
}
}
return node.word;
}
/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
public boolean search(String word) {
return search(word, 0, root);
}
}
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary obj = new WordDictionary();
* obj.addWord(word);
* boolean param_2 = obj.search(word);
*/