Skip to content

Instantly share code, notes, and snippets.

@AliOsm
Created July 1, 2022 17:45
Show Gist options
  • Save AliOsm/98efb6222af088643f005e36ecb328fc to your computer and use it in GitHub Desktop.
Save AliOsm/98efb6222af088643f005e36ecb328fc to your computer and use it in GitHub Desktop.
Trie data structure using pointers
#include <bits/stdc++.h>
using namespace std;
int n, m;
string s;
struct trie {
trie *next[26];
int count;
bool end;
trie() {
memset(next, 0, sizeof next);
count = 0;
end = false;
}
};
trie *root;
void insert(string s) {
trie *current = root;
for(int i = 0; i < s.length(); ++i) {
int idx = s[i] - 'a';
if(current->next[idx] == NULL) {
current->next[idx] = new trie();
}
current = current->next[idx];
++current->count;
}
current->end = true;
}
bool find(string s) {
trie *current = root;
for(int i = 0; i < s.length(); ++i) {
int idx = s[i] - 'a';
if(current->next[idx] == NULL) {
return false;
}
current = current->next[idx];
}
return current->end;
}
void freeTrie(trie *current) {
if(current == NULL) {
return;
}
for(int i = 0; i < 26; ++i) {
freeTrie(current->next[i]);
}
delete [] current;
}
int main() {
#ifndef ONLINE_JUDGE
freopen("input.in", "r", stdin);
#endif
root = new trie();
scanf("%d %d", &n, &m);
for(int i = 0; i < n; i++) {
cin >> s;
insert(s);
}
for(int i = 0; i < m; ++i) {
cin >> s;
if(find(s)) {
puts("YES");
} else {
puts("NO");
}
}
freeTrie(root);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment