Advertisement
SalmaYasser

Untitled

Dec 22nd, 2019
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. class TrieNode
  2. {
  3. public:
  4. TrieNode *next[26];
  5. bool is_word;
  6.  
  7. // Initialize your data structure here.
  8. TrieNode(bool b = false)
  9. {
  10. memset(next, 0, sizeof(next));
  11. is_word = b;
  12. }
  13. };
  14.  
  15. class Trie
  16. {
  17. TrieNode *root;
  18. public:
  19. Trie()
  20. {
  21. root = new TrieNode();
  22. }
  23.  
  24. // Inserts a word into the trie.
  25. void insert(string s)
  26. {
  27. TrieNode *p = root;
  28. for(int i = 0; i < s.size(); ++ i)
  29. {
  30. if(p -> next[s[i] - 'a'] == NULL)
  31. p -> next[s[i] - 'a'] = new TrieNode();
  32. p = p -> next[s[i] - 'a'];
  33. }
  34. p -> is_word = true;
  35. }
  36.  
  37. // Returns if the word is in the trie.
  38. bool search(string key)
  39. {
  40. TrieNode *p = find(key);
  41. return p != NULL && p -> is_word;
  42. }
  43.  
  44. // Returns if there is any word in the trie
  45. // that starts with the given prefix.
  46. bool startsWith(string prefix)
  47. {
  48. return find(prefix) != NULL;
  49. }
  50.  
  51. private:
  52. TrieNode* find(string key)
  53. {
  54. TrieNode *p = root;
  55. for(int i = 0; i < key.size() && p != NULL; ++ i)
  56. p = p -> next[key[i] - 'a'];
  57. return p;
  58. }
  59. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement