Created
April 15, 2016 19:21
-
-
Save arknave/f68f9f0a4e8bd37b8c5f7965c5b66d31 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <cstring> | |
#define MAX_LETTERS 600005 | |
#define ALPHABET_SIZE 26 | |
using namespace std; | |
// These two structures should be intiialized to all 0 | |
// (0 is the root and should never be the child of another node) | |
int trie[MAX_LETTERS][ALPHABET_SIZE]; | |
bool end_word[MAX_LETTERS]; | |
int next_node = 1; | |
// insert string s at the root of the trie | |
void insert(string s) { | |
int len = s.size(); | |
int node = 0; | |
for (int i = 0; i < len; ++i) { | |
int child = s[i] - 'a'; | |
if (trie[node][child] == 0) | |
trie[node][child] = next_node++; | |
node = trie[node][child]; | |
} | |
end_word[node] = true; | |
} | |
// check if the trie contains string s | |
bool contains(string s) { | |
int len = s.size(); | |
int node = 0; | |
for (int i = 0; i < len; ++i) { | |
int child = s[i] - 'a'; | |
if (trie[node][child] == 0) | |
return false; | |
node = trie[node][child]; | |
} | |
return end_word[node]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment