Last active
April 13, 2019 04:05
-
-
Save Chillee/8a7cb187a3e906c81c6e840bccbb134b to your computer and use it in GitHub Desktop.
Trie
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
struct Trie { | |
const static int MAXCHAR = 26; | |
struct Vertex { | |
int nxt[MAXCHAR]; | |
bool leaf = false; | |
Vertex() { fill(begin(nxt), end(nxt), -1); } | |
int &operator[](int x) { return nxt[x]; } | |
}; | |
Trie() : trie(1) {} | |
vector<Vertex> trie; | |
Vertex &operator[](int x) { return trie[x]; } | |
void add_string(string const &s) { | |
int v = 0; | |
for (char ch : s) { | |
int c = ch - 'a'; | |
if (trie[v][c] == -1) { | |
trie[v][c] = trie.size(); | |
trie.emplace_back(); | |
} | |
v = trie[v][c]; | |
} | |
trie[v].leaf = true; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment