Leetcode 211. Design Add and Search Words Data Structure
You need to design a data structure for adding and searching words efficiently. The data structure should support the following two operations:
void addWord(String word): Adds a word into the data structure.boolean search(String word): Returns true if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.'.' appear multiple times in a single search query?
'.' character can appear multiple times and at any positions within the search query.We will use a Trie (prefix tree) data structure. This will help us efficiently store and search words with support for the dot character '.'.
Here’s how you can implement the data structure in Java:
class WordDictionary {
private class TrieNode {
public TrieNode[] children;
public boolean isWord;
public TrieNode() {
this.children = new TrieNode[26]; // for 26 lowercase English letters
this.isWord = false;
}
}
private TrieNode root;
public WordDictionary() {
this.root = new TrieNode();
}
public void addWord(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
int index = c - 'a';
if (node.children[index] == null) {
node.children[index] = new TrieNode();
}
node = node.children[index];
}
node.isWord = true; // mark the end of a word
}
public boolean search(String word) {
return searchInNode(word, root, 0);
}
private boolean searchInNode(String word, TrieNode node, int start) {
TrieNode current = node;
for (int i = start; i < word.length(); i++) {
char c = word.charAt(i);
if (c == '.') {
// Check all possible children nodes
for (TrieNode child : current.children) {
if (child != null && searchInNode(word, child, i + 1)) {
return true;
}
}
return false; // if no path matched
} else {
int index = c - 'a';
if (current.children[index] == null) {
return false;
}
current = current.children[index];
}
}
return current.isWord;
}
}
'.' character requires checking all 26 possible children nodes.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?