2023-03-19 Daily Challenge
Today I have done leetcode's March LeetCoding Challenge with cpp.
March LeetCoding Challenge 19
Description
Design Add and Search Words Data Structure
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)Addswordto the data structure, it can be matched later.bool search(word)Returnstrueif there is any string in the data structure that matcheswordorfalseotherwise.wordmay 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 <= 25wordinaddWordconsists of lowercase English letters.wordinsearchconsist of'.'or lowercase English letters.- There will be at most
3dots inwordforsearchqueries. - At most
104calls will be made toaddWordandsearch.
Solution
auto speedup = [](){
cin.tie(nullptr);
cout.tie(nullptr);
ios::sync_with_stdio(false);
return 0;
}();
struct TrieNode {
bool end = false;
TrieNode *children[26] = {};
};
class WordDictionary {
TrieNode *root;
bool helper(const string &word, TrieNode *cur, int pos = 0) {
int len = word.length();
for(int i = pos; i < len; ++i) {
if(word[i] != '.') {
if(!cur->children[word[i] - 'a']) return false;
cur = cur->children[word[i] - 'a'];
} else {
for(auto child : cur->children) {
if(child && helper(word, child, i + 1)) return true;
}
return false;
}
}
return cur->end;
}
public:
WordDictionary() {
root = new TrieNode();
}
void addWord(string word) {
TrieNode *cur = root;
for(auto c : word) {
c -= 'a';
if(!cur->children[c]) {
cur->children[c] = new TrieNode();
}
cur = cur->children[c];
}
cur->end = true;
}
bool search(string word) {
return helper(word, root);
}
};
// Accepted
// 29/29 cases passed (859 ms)
// Your runtime beats 94.41 % of cpp submissions
// Your memory usage beats 72.66 % of cpp submissions (558.4 MB)