Skip to content

Instantly share code, notes, and snippets.

@dabasajay
Last active February 14, 2021 17:32
Show Gist options
  • Save dabasajay/a7adf9f4cd10039a5db7a73a4eb995b7 to your computer and use it in GitHub Desktop.
Save dabasajay/a7adf9f4cd10039a5db7a73a4eb995b7 to your computer and use it in GitHub Desktop.
dsa/strings | desc: Trie Data Structure
class Node {
public:
vector<Node*> children;
bool isLeaf;
Node() {
children.assign(26, NULL);
isLeaf = false;
}
};
class Trie {
public:
Node *root;
/** Initialize your data structure here. */
Trie() {
root = new Node();
}
/** Inserts a word into the trie. */
void insert(string word) {
Node *node = root;
for (int i = 0; i < word.length(); i++) {
int idx = word[i] - 'a';
if (!node -> children[idx])
node -> children[idx] = new Node();
node = node -> children[idx];
}
node -> isLeaf = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
Node *node = root;
for (int i = 0; i < word.length(); i++) {
int idx = word[i] - 'a';
if (!node -> children[idx])
return false;
node = node -> children[idx];
}
return node -> isLeaf == true;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
Node *node = root;
for (int i = 0; i < prefix.length(); i++) {
int idx = prefix[i] - 'a';
if (!node -> children[idx])
return false;
node = node -> children[idx];
}
return true;
}
};
@dabasajay
Copy link
Author

dabasajay commented Feb 14, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment