LeetCode Solutions
211. Design Add and Search Words Data Structure
Time: Space:
struct TrieNode {
vector<shared_ptr<TrieNode>> children;
bool isWord = false;
TrieNode() : children(26) {}
};
class WordDictionary {
public:
void addWord(const string& word) {
shared_ptr<TrieNode> node = root;
for (const char c : word) {
const int i = c - 'a';
if (node->children[i] == nullptr)
node->children[i] = make_shared<TrieNode>();
node = node->children[i];
}
node->isWord = true;
}
bool search(const string& word) {
return dfs(word, 0, root);
}
private:
shared_ptr<TrieNode> root = make_shared<TrieNode>();
bool dfs(const string& word, int s, shared_ptr<TrieNode> node) {
if (s == word.length())
return node->isWord;
if (word[s] != '.') {
shared_ptr<TrieNode> next = node->children[word[s] - 'a'];
return next ? dfs(word, s + 1, next) : false;
}
// word[s] == '.' -> search all 26 children
for (int i = 0; i < 26; ++i)
if (node->children[i] && dfs(word, s + 1, node->children[i]))
return true;
return false;
}
};
class TrieNode {
public TrieNode[] children = new TrieNode[26];
public boolean isWord = false;
}
class WordDictionary {
public void addWord(String word) {
TrieNode node = root;
for (final char c : word.toCharArray()) {
final int i = c - 'a';
if (node.children[i] == null)
node.children[i] = new TrieNode();
node = node.children[i];
}
node.isWord = true;
}
public boolean search(String word) {
return dfs(word, 0, root);
}
private TrieNode root = new TrieNode();
private boolean dfs(String word, int s, TrieNode node) {
if (s == word.length())
return node.isWord;
if (word.charAt(s) != '.') {
TrieNode next = node.children[word.charAt(s) - 'a'];
return next == null ? false : dfs(word, s + 1, next);
}
// Word.charAt(s) == '.' -> search all 26 children
for (int i = 0; i < 26; ++i)
if (node.children[i] != null && dfs(word, s + 1, node.children[i]))
return true;
return false;
}
}
class TrieNode:
def __init__(self):
self.children: Dict[str, TrieNode] = defaultdict(TrieNode)
self.isWord = False
class WordDictionary:
def __init__(self):
self.root = TrieNode()
def addWord(self, word: str) -> None:
node: TrieNode = self.root
for c in word:
if c not in node.children:
node.children[c] = TrieNode()
node = node.children[c]
node.isWord = True
def search(self, word: str) -> bool:
return self._dfs(word, 0, self.root)
def _dfs(self, word: str, s: int, node: TrieNode) -> bool:
if s == len(word):
return node.isWord
if word[s] != '.':
next: TrieNode = node.children[word[s]]
return self._dfs(word, s + 1, next) if next else False
for c in string.ascii_lowercase:
if c in node.children and self._dfs(word, s + 1, node.children[c]):
return True
return False