Nxt pointer using a static array of design, probably as the nxt pointer than using a map designed to be twice as fast, but also a large space cost about 1 times. In the case where a small amount of data, and time and space efficiency is not map <vector
Time Complexity:
Initialization: O (sigma)
insert: O (len * sigma)
query: O (len)
Space complexity:
O (n-* len * Sigma)
struct TrieNode {
int data;
int nxt[26];
void init() {
data = 0;
memset(nxt, 0, sizeof(nxt));
}
};
struct Trie {
TrieNode tn[200005];
int root, top;
int newnode() {
tn[++top].init();
return top;
}
void init() {
top = 0;
root = newnode();
}
void insert(int *a, int len, int data) {
int cur = root;
for(int i = 1; i <= len; ++i) {
int &nxt = tn[cur].nxt[a[i] - 'a'];
if(!nxt)
nxt = newnode();
cur = nxt;
}
tn[cur].data = data;
}
int query(int *a, int len) {
int cur = root;
for(int i = 1; i <= len; ++i) {
int &nxt = tn[cur].nxt[a[i] - 'a'];
if(!nxt)
return -1;
cur = nxt;
}
return tn[cur].data;
}
} trie;