Commit f0551119 by 李楚霏

week7-work1

parent 855cb035
class Trie {
struct TrieNode {
map<char, TrieNode*> child_table;
int end;
TrieNode():end(0) {};
};
public:
/** Initialize your data structure here. */
Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
void insert(string word) {
TrieNode* cur = root;
for(int i =0; i < word.size(); i++) {
if(cur->child_table.count(word[i]) == 0) {
cur->child_table[word[i]] = new TrieNode();
}
cur =cur->child_table[word[i]];
}
cur->end=1;
}
/** Returns if the word is in the trie. */
bool search(string word) {
return find(word, 1);
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
return find(prefix, 0);
}
private:
TrieNode *root;
bool find(string prefix, int exact_match) {
TrieNode *cur = root;
for(int i =0; i<prefix.size(); i++) {
if(cur->child_table.count(prefix[i]) == 0) {
return false;
}
cur = cur->child_table[prefix[i]];
}
if(exact_match) {
return cur->end? true: false;
}
return true;
}
};
/**
* Your Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* bool param_2 = obj->search(word);
* bool param_3 = obj->startsWith(prefix);
*/
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment