Last active
February 14, 2021 17:32
-
-
Save dabasajay/a7adf9f4cd10039a5db7a73a4eb995b7 to your computer and use it in GitHub Desktop.
dsa/strings | desc: Trie Data Structure
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
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; | |
} | |
}; |
Author
dabasajay
commented
Feb 14, 2021
•
- Maximum XOR of Two Numbers in an Array - Trie + Bitmasking
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment