forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
89 lines (65 loc) · 1.61 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/// Source : https://leetcode.com/problems/stream-of-characters/
/// Author : liuyubobobo
/// Time : 2019-04-20
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
/// Trie
/// Time Complexity: init: O(n * |word|)
/// query: O(max length of words)
/// Space Complexity: O(n * |word| + |q|)
class Trie {
private:
struct Node{
unordered_map<char, int> next;
bool end = false;
};
vector<Node> trie;
public:
Trie(){
trie.clear();
trie.push_back(Node());
}
void insert(const string& word){
int treeID = 0;
for(char c: word){
if(trie[treeID].next.find(c) == trie[treeID].next.end()){
trie[treeID].next[c] = trie.size();
trie.push_back(Node());
}
treeID = trie[treeID].next[c];
}
trie[treeID].end = true;
}
bool search(const string& q){
int treeID = 0;
for(int i = q.size() - 1; i >= 0; i --){
if(trie[treeID].end) return true;
char c = q[i];
if(!trie[treeID].next.count(c))
return false;
treeID = trie[treeID].next[c];
}
return trie[treeID].end;
}
};
class StreamChecker {
private:
Trie trie;
string q = "";
public:
StreamChecker(vector<string>& words){
for(string& word: words){
reverse(word.begin(), word.end());
trie.insert(word);
}
}
bool query(char letter) {
q += letter;
return trie.search(q);
}
};
int main() {
return 0;
}