/** Inserts a word into the trie. */ voidinsert(string word){ TrieNode* temp = root; for(int i = 0; i < word.length(); i++){ int cind = word[i] - 'a'; if(!temp->alpha[cind]){ temp->alpha[cind] = new TrieNode(); } temp = temp->alpha[cind]; } temp->end = true; }
/** Returns if the word is in the trie. */ boolsearch(string word){ TrieNode* temp = root; for(char c : word){ int cind = c - 'a'; if(!temp->alpha[cind]) returnfalse; temp = temp->alpha[cind]; } if(!temp->end) returnfalse;
returntrue; }
/** Returns if there is any word in the trie that starts with the given prefix. */ boolstartsWith(string prefix){ TrieNode* temp = root; for(char c : prefix){ int cind = c - 'a'; if(!temp->alpha[cind]) returnfalse; temp = temp->alpha[cind]; } returntrue; } };
近期评论