208. Implement Trie (Prefix Tree)

来源:互联网 发布:nano接收器配对软件 编辑:程序博客网 时间:2024/06/05 14:13

Implement a trie with insertsearch, and startsWith methods.

Note:
You may assume that all inputs are consist of lowercase letters a-z.

class TrieNode {public:// Initialize your data structure here.TrieNode():isExit(false){/*for (int i = 0; i < 26; i++)next[i] = NULL;*/memset(next, 0, sizeof(next));}bool isExit;TrieNode* next[26];};class Trie {public:Trie() {root = new TrieNode();}// Inserts a word into the trie.void insert(string word) {TrieNode* p = root;for (int i = 0; i < word.size(); i++){if (p->next[word[i]-'a'] != NULL){p = p->next[word[i] - 'a'];}else{p->next[word[i] - 'a'] = new TrieNode();p = p->next[word[i] - 'a'];}}p->isExit = true;}// Returns if the word is in the trie.bool search(string word) {TrieNode* p = root;for (int i = 0; i < word.size(); i++){if (p->next[word[i] - 'a'] != NULL){p = p->next[word[i] - 'a'];}else{return false;}}if (p->isExit)return true;return false;}// Returns if there is any word in the trie// that starts with the given prefix.bool startsWith(string prefix) {TrieNode* p = root;for (int i = 0; i < prefix.size(); i++){if (p->next[prefix[i]-'a'] != NULL){p = p->next[prefix[i]-'a'];}else{return false;}}return true;}private:TrieNode* root;};// Your Trie object will be instantiated and called as such:// Trie trie;// trie.insert("somestring");// trie.search("key");



0 0
原创粉丝点击