Last active
July 10, 2016 15:19
-
-
Save wweic/d310d0cbd76a53e389fddecd4f9e7b14 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 <algorithm> | |
| #include <iostream> | |
| #include <string> | |
| using namespace std; | |
| class TrieNode { | |
| public: | |
| // Initialize your data structure here. | |
| TrieNode(): end(false) { | |
| fill_n(node, 26, nullptr); | |
| } | |
| TrieNode* node[26]; | |
| bool end; | |
| }; | |
| class Trie { | |
| public: | |
| Trie() { | |
| root = new TrieNode(); | |
| } | |
| // Inserts a word into the trie. | |
| void insert(string word) { | |
| TrieNode* current = root; | |
| for (size_t i = 0; i < word.size(); i++) { | |
| if ((current->node)[word[i] - 'a'] == NULL) { | |
| (current->node)[word[i] - 'a'] = new TrieNode(); | |
| } | |
| current = (current->node)[word[i] - 'a']; | |
| } | |
| current->end = true; | |
| return; | |
| } | |
| // Returns if the word is in the trie. | |
| bool search(string word) { | |
| TrieNode* current = root; | |
| for (size_t i = 0; i < word.length(); i++) { | |
| if ((current->node)[word[i] - 'a'] == NULL) { | |
| return false; | |
| } | |
| current = (current->node)[word[i] - 'a']; | |
| } | |
| return current->end; | |
| } | |
| // Returns if there is any word in the trie | |
| // that starts with the given prefix. | |
| bool startsWith(string prefix) { | |
| TrieNode* current = root; | |
| for (size_t i = 0; i < prefix.length(); i++) { | |
| if ((current->node)[prefix[i] - 'a'] == NULL) { | |
| return false; | |
| } | |
| current = (current->node)[prefix[i] - 'a']; | |
| } | |
| return true; | |
| } | |
| private: | |
| TrieNode* root; | |
| }; | |
| int main() { | |
| Trie trie; | |
| trie.insert("key"); | |
| if (trie.search("key")) { | |
| cout << "found" << endl; | |
| } else { | |
| cout << "not found" << endl; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment