Advertisement
Jasir

Trie (dynamic allocation)

May 7th, 2018 (edited)
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.38 KB | None | 0 0
  1. struct trie{
  2.     trie* child[27];
  3.     trie(){
  4.         for(int i=0;i<27;i++){
  5.             child[i] = NULL;
  6.         }
  7.     }
  8. };
  9.  
  10. class Trie {
  11. public:
  12.     /** Initialize your data structure here. */
  13.     trie* root;
  14.     Trie() {
  15.         root = new trie;
  16.     }
  17.    
  18.     /** Inserts a word into the trie. */
  19.     void insert(string word) {
  20.         trie* cur =  root;
  21.         for(int i=0;i<word.length();i++){
  22.             if((cur->child[word[i]-'a'])==NULL){
  23.                 cur->child[word[i]-'a'] = new trie;
  24.             }
  25.             cur = cur->child[word[i]-'a'];
  26.         }
  27.         cur->child[26] = new trie;
  28.     }
  29.    
  30.     /** Returns if the word is in the trie. */
  31.     bool search(string word) {
  32.         trie* cur =  root;
  33.         for(int i=0;i<word.length();i++){
  34.             if((cur->child[word[i]-'a'])==NULL){
  35.                 return false;
  36.             }
  37.             cur = cur->child[word[i]-'a'];
  38.         }
  39.         if( cur->child[26]) return true;
  40.         return false;
  41.     }
  42.    
  43.     /** Returns if there is any word in the trie that starts with the given prefix. */
  44.     bool startsWith(string prefix) {
  45.         trie* cur =  root;
  46.         for(int i=0;i<prefix.length();i++){
  47.             if((cur->child[prefix[i]-'a'])==NULL){
  48.                 return false;
  49.             }
  50.             cur = cur->child[prefix[i]-'a'];
  51.         }
  52.         return true;
  53.     }
  54. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement