fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. struct TrieNode {
  5. bool we;
  6. TrieNode *child[26];
  7. TrieNode(){
  8. we=false;
  9. for(int i=0;i<26;i++) { child[i] = nullptr; }
  10. }
  11. };
  12.  
  13. void insert(TrieNode* root, string str) {
  14. TrieNode* curr = root;
  15. for(char c : str) {
  16. if(curr->child[c-'a'] == nullptr) {
  17. TrieNode* nn = new TrieNode();
  18. curr->child[c-'a'] = nn;
  19. }
  20. curr = curr->child[c-'a'];
  21. }
  22. curr->we = 1;
  23. // cout<<"Insertion Done"<<endl;
  24. }
  25.  
  26. bool search(TrieNode *root, string str) {
  27. TrieNode *curr = root;
  28. for(char ch : str) {
  29. if(curr->child[ch-'a'] == nullptr) return false;
  30. curr = curr->child[ch-'a'];
  31. }
  32. return curr->we;
  33. }
  34.  
  35. int main() {
  36. TrieNode* root = new TrieNode();
  37. vector<string> keys = {"and","ant","do","dose"};
  38. for(auto word : keys) {
  39. insert(root, word);
  40. }
  41. cout<< search(root,"bose")<<endl;
  42. return 0;
  43. }
Success #stdin #stdout 0s 5284KB
stdin
Standard input is empty
stdout
0