Skip to content

Commit

Permalink
add Trie
Browse files Browse the repository at this point in the history
  • Loading branch information
gzc committed Jul 30, 2017
1 parent 83c8578 commit e61c6ae
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 1 deletion.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -285,8 +285,9 @@ If a problem is too easy to solve, we'll mark it as **straightforward** in order
* [RBT](./C13-Red-Black-Trees/rbtree.cpp)
* [Btree](./C18-B-Trees/btree.cpp)
* [BinomialHeap](./C19-Binomial-Heaps/BinomialHeap.h) [Driver](././C19-Binomial-Heaps/Main.cpp)
* [UnionFind](./C21-Data-Structures-for-Disjoint-Sets/uf.cpp)
* [SegmentTree](./other/segmentTree.cpp)
* [Trie](./other/trie.cpp)
* [UnionFind](./C21-Data-Structures-for-Disjoint-Sets/uf.cpp)

### DYNAMIC/GREEDY
* [Matrix Chain](./C15-Dynamic-Programming/Matrix-chain-multiplication.c)
Expand Down
59 changes: 59 additions & 0 deletions other/trie.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
struct TrieNode {
TrieNode *nodes[26];
bool word;
// Initialize your data structure here.
TrieNode(): word(false) {
memset(nodes, 0, sizeof(nodes));
}
};

class Trie {

public:
Trie() {
root = new TrieNode();
}

// Inserts a word into the trie.
void insert(const string& s) {
TrieNode *tmp = root;
for(char ch : s) {
int index = ch - 'a';
if(tmp->nodes[index] == nullptr) {
tmp->nodes[index] = new TrieNode();
}
tmp = tmp->nodes[index];
}
tmp->word = true;
}

// Returns if the word is in the trie.
bool search(const string& key) const {
TrieNode *tmp = root;
for(char ch : key) {
int index = ch - 'a';
if(tmp->nodes[index] == nullptr) {
return false;
}
tmp = tmp->nodes[index];
}
return tmp->word;
}

// Returns if there is any word in the trie
// that starts with the given prefix.
bool startsWith(const string& prefix) const {
TrieNode *tmp = root;
for(char ch : prefix) {
int index = ch - 'a';
if(tmp->nodes[index] == nullptr) {
return false;
}
tmp = tmp->nodes[index];
}
return true;
}

private:
TrieNode* root;
};

0 comments on commit e61c6ae

Please sign in to comment.