Design a data structure that supports adding new words and finding if a string matches any previously added string.
Implement the WordDictionary
class:
WordDictionary()
Initializes the object.void addWord(word)
Addsword
to the data structure, it can be matched later.bool search(word)
Returnstrue
if there is any string in the data structure that matchesword
orfalse
otherwise.word
may contain dots'.'
where dots can be matched with any letter.
Example:
Input ["WordDictionary","addWord","addWord","addWord","search","search","search","search"] [[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]] Output [null,null,null,null,false,true,true,true] Explanation WordDictionary wordDictionary = new WordDictionary(); wordDictionary.addWord("bad"); wordDictionary.addWord("dad"); wordDictionary.addWord("mad"); wordDictionary.search("pad"); // return False wordDictionary.search("bad"); // return True wordDictionary.search(".ad"); // return True wordDictionary.search("b.."); // return True
Constraints:
1 <= word.length <= 500
word
inaddWord
consists lower-case English letters.word
insearch
consist of'.'
or lower-case English letters.- At most
50000
calls will be made toaddWord
andsearch
.
Companies:
Facebook, Amazon, Google, Oracle, Apple, Microsoft
Related Topics:
String, Depth-First Search, Design, Trie
Similar Questions:
// OJ: https://leetcode.com/problems/add-and-search-word-data-structure-design/
// Author: github.com/lzl124631x
// Time:
// WordDictionary: O(1)
// addWord: O(W)
// search: O(26^W)
// Space: O(NW)
struct TrieNode {
TrieNode *next[26] = {};
bool end = false;
};
class WordDictionary {
TrieNode root;
bool dfs(TrieNode *node, string &word, int i) {
if (!node) return false;
if (i == word.size()) return node->end;
if (word[i] != '.') return dfs(node->next[word[i] - 'a'], word, i + 1);
for (int j = 0; j < 26; ++j) {
if (dfs(node->next[j], word, i + 1)) return true;
}
return false;
}
public:
void addWord(string word) {
auto node = &root;
for (char c : word) {
if (!node->next[c - 'a']) node->next[c - 'a'] = new TrieNode();
node = node->next[c - 'a'];
}
node->end = true;
}
bool search(string word) {
return dfs(&root, word, 0);
}
};
// OJ: https://leetcode.com/problems/add-and-search-word-data-structure-design/
// Author: github.com/lzl124631x
// Time:
// WordDictionary: O(1)
// addWord: O(1)
// search: O(NW)
// Space: O(NW)
class WordDictionary {
unordered_map<int, vector<string>> m;
public:
void addWord(string word) {
m[word.size()].push_back(word);
}
bool search(string word) {
if (m.count(word.size()) == 0) return false;
for (auto s : m[word.size()]) {
int i = 0;
for (; i < word.size(); ++i) {
if (word[i] != '.' && word[i] != s[i]) break;
}
if (i == word.size()) return true;
}
return false;
}
};