1
+ #include < iostream>
2
+ #include < vector>
3
+ #include < string>
4
+ using namespace std ;
5
+ class Trie
6
+ {
7
+ public:
8
+ vector<Trie*> x;
9
+ Trie ():x(26 ){}
10
+ string word;
11
+ };
12
+ Trie *root;
13
+ void addWord (string word)
14
+ {
15
+ Trie *temp=root;
16
+ for (int i=0 ;i<word.size ();i++)
17
+ {
18
+ if (temp->x [word[i]-' a' ]==NULL )
19
+ temp->x [word[i]-' a' ]= new Trie;
20
+ temp=temp->x [word[i]-' a' ];
21
+ if (i+1 ==word.size ())
22
+ temp->word =word;
23
+ }
24
+ }
25
+ void searchtrie (string word,Trie* temp,bool &v,int start)
26
+ {
27
+ if (temp->word .size ()==word.size ())
28
+ v=true ;
29
+ else
30
+ {
31
+ for (int i=start;i<word.size ()&&v==false ;i++)
32
+ {
33
+ if (word[i]==' .' )
34
+ {
35
+ for (int j=0 ;j<26 &&v==false ;j++)
36
+ if (temp->x [j]!=NULL )
37
+ searchtrie (word,temp->x [j],v,i+1 );
38
+ }
39
+ else
40
+ {
41
+ if (temp->x [word[i]-' a' ]!=NULL )
42
+ {
43
+ temp=temp->x [word[i]-' a' ];
44
+ if (temp->word .size ()==word.size ())
45
+ v=true ;
46
+ }
47
+ else
48
+ break ;
49
+ }
50
+ }
51
+ }
52
+ }
53
+ bool search (string word)
54
+ {
55
+ bool v=false ;
56
+ Trie *temp=root;
57
+ searchtrie (word,temp,v,0 );
58
+ return v;
59
+ }
60
+ int main ()
61
+ {
62
+ root=new Trie;
63
+ int present;
64
+ vector<string> words={" Hello" ," World" ," C++Program" }; // Sample Input
65
+ vector<string> find={" World" ," Program" };
66
+ for (int i=0 ;i<words.size ();i++)
67
+ addWord (words[i]);
68
+ for (int i=0 ;i<find.size ();i++)
69
+ {
70
+ present=search (find[i]);
71
+ if (!present)
72
+ printf (" Word not Found :(\n " );
73
+ else
74
+ printf (" Found the Word :)\n " );
75
+ }
76
+ return 0 ;
77
+ }
0 commit comments