Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- struct trie{
- trie* child[27];
- trie(){
- for(int i=0;i<27;i++){
- child[i] = NULL;
- }
- }
- };
- class Trie {
- public:
- /** Initialize your data structure here. */
- trie* root;
- Trie() {
- root = new trie;
- }
- /** Inserts a word into the trie. */
- void insert(string word) {
- trie* cur = root;
- for(int i=0;i<word.length();i++){
- if((cur->child[word[i]-'a'])==NULL){
- cur->child[word[i]-'a'] = new trie;
- }
- cur = cur->child[word[i]-'a'];
- }
- cur->child[26] = new trie;
- }
- /** Returns if the word is in the trie. */
- bool search(string word) {
- trie* cur = root;
- for(int i=0;i<word.length();i++){
- if((cur->child[word[i]-'a'])==NULL){
- return false;
- }
- cur = cur->child[word[i]-'a'];
- }
- if( cur->child[26]) return true;
- return false;
- }
- /** Returns if there is any word in the trie that starts with the given prefix. */
- bool startsWith(string prefix) {
- trie* cur = root;
- for(int i=0;i<prefix.length();i++){
- if((cur->child[prefix[i]-'a'])==NULL){
- return false;
- }
- cur = cur->child[prefix[i]-'a'];
- }
- return true;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement