Leetcode 211. Design Add and Search Words Data Structure
Design a data structure that supports the following two operations:
void addWord(word)
: Adds a word into the data structure.bool search(word)
: Returns true
if there is any string in the data structure that matches word
or false
otherwise. The word may contain dots '.'
where dots can be matched with any letter.Implement the WordDictionary
class:
class WordDictionary {
public:
WordDictionary();
void addWord(string word);
bool search(string word);
};
addWord
and search
functions?'.'
:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class TrieNode {
public:
bool isWord;
TrieNode* children[26];
TrieNode() : isWord(false) {
for (int i = 0; i < 26; ++i) {
children[i] = nullptr;
}
}
};
class WordDictionary {
private:
TrieNode* root;
bool searchInNode(string& word, int index, TrieNode* node) {
if (index == word.length()) {
return node->isWord;
}
char c = word[index];
if (c == '.') {
for (int i = 0; i < 26; ++i) {
if (node->children[i] && searchInNode(word, index + 1, node->children[i])) {
return true;
}
}
return false;
} else {
int childIndex = c - 'a';
return node->children[childIndex] && searchInNode(word, index + 1, node->children[childIndex]);
}
}
public:
WordDictionary() {
root = new TrieNode();
}
void addWord(string word) {
TrieNode* currentNode = root;
for (char c : word) {
int index = c - 'a';
if (!currentNode->children[index]) {
currentNode->children[index] = new TrieNode();
}
currentNode = currentNode->children[index];
}
currentNode->isWord = true;
}
bool search(string word) {
return searchInNode(word, 0, root);
}
};
// Example usage:
// int main() {
// WordDictionary wordDictionary;
// wordDictionary.addWord("bad");
// wordDictionary.addWord("dad");
// wordDictionary.addWord("mad");
// cout << wordDictionary.search("pad") << endl; // Should return false
// cout << wordDictionary.search("bad") << endl; // Should return true
// cout << wordDictionary.search(".ad") << endl; // Should return true
// cout << wordDictionary.search("b..") << endl; // Should return true
// return 0;
// }
n
is the length of the word. Each character of the word is inserted into the Trie.m
is the length of the word and d
is the number of dots. In a realistic scenario, the search is much faster due to the branching factor.N
is the number of words and L
is the average length of the words. Each node carries an array of 26 pointers, but not all are used.This design leverages the Trie structure to efficiently manage and search words, providing flexibility to handle the dot wildcard in the search queries effectively.
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?