classTrie { public: int son[100010][26], ok[100010]; int idx; /** Initialize your data structure here. */ Trie() { memset(son, 0 ,sizeof(son)); memset(ok,0,sizeof(ok)); }
/** Inserts a word into the trie. */ voidinsert(string word){ int p=0; for(auto c:word) { int u=c-'a'; if(!son[p][u]) son[p][u]=++idx; p=son[p][u]; } ok[p]=1; }
/** Returns if the word is in the trie. */ boolsearch(string word){ int p=0; for(auto c:word) { int u=c-'a'; if(!son[p][u]) returnfalse; p=son[p][u]; } return ok[p]; }
/** Returns if there is any word in the trie that starts with the given prefix. */ boolstartsWith(string prefix){ int p=0; for(auto c:prefix) { int u=c-'a'; if(!son[p][u]) returnfalse; p=son[p][u]; } returntrue; } };
/** * 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); */