Skip to content

Commit a7d104d

Browse files
🎉 Day 23
1 parent cba5b20 commit a7d104d

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737
## Week 4 🚧
3838

3939
1. [Random Point in Non-overlapping Rectangles](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge/552/week-4-august-22nd-august-28th/3433/) ➡️ [CPP Solution](Week4/randomPoint.cpp)
40+
2. [Stream of Characters](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge/552/week-4-august-22nd-august-28th/3434/) ➡️ [CPP Solution](Week4/streamChecker.cpp)
4041

4142
## Week 5 🚧
4243

Week4/streamChecker.cpp

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
class StreamChecker {
2+
private:
3+
class Trie {
4+
public:
5+
bool is_leaf;
6+
Trie* children[26];
7+
8+
Trie() {
9+
this->is_leaf = false;
10+
for(int i = 0; i < 26; ++i) {
11+
this->children[i] = NULL;
12+
}
13+
}
14+
15+
void insert_reversed(string word) {
16+
reverse(word.begin(), word.end());
17+
Trie* root = this;
18+
19+
for(char c: word) {
20+
int idx = c - 'a';
21+
22+
if(root->children[idx] == NULL)
23+
root->children[idx] = new Trie();
24+
25+
root = root->children[idx];
26+
}
27+
28+
root->is_leaf = true;
29+
}
30+
31+
};
32+
public:
33+
Trie trie;
34+
vector<char> queries;
35+
int longest_word = 0;
36+
37+
StreamChecker(vector<string>& words) {
38+
for(auto& word: words) {
39+
trie.insert_reversed(word);
40+
41+
if(word.size() > longest_word)
42+
longest_word = word.size();
43+
}
44+
}
45+
46+
bool query(char letter) {
47+
queries.insert(queries.begin(), letter);
48+
49+
if(queries.size() > longest_word)
50+
queries.pop_back();
51+
52+
Trie* curr = &trie;
53+
54+
for(char c: queries) {
55+
if(curr->is_leaf) return true;
56+
if(curr->children[c - 'a'] == NULL) return false;
57+
58+
curr = curr->children[c - 'a'];
59+
}
60+
61+
return curr->is_leaf;
62+
}
63+
};
64+
65+
/**
66+
* Your StreamChecker object will be instantiated and called as such:
67+
* StreamChecker* obj = new StreamChecker(words);
68+
* bool param_1 = obj->query(letter);
69+
*/

0 commit comments

Comments
 (0)