-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTrieTree.cpp
63 lines (56 loc) · 1.19 KB
/
TrieTree.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include<iostream>
using namespace std;
class Node {
bool isEnd;
Node*alp[27]={NULL};
friend class TrieTree;
public:
Node() {
isEnd=false;
}
};
class TrieTree {
Node*root;
public:
TrieTree() {
root=new Node();
}
void insert(string s) {
int c;
Node*q=root,*r=root;
for(int i=0;s[i]!='\0';i++) {
c=s[i]-'a';
if(!q->alp[c]) {
Node*p=new Node();
q->alp[c]=p;
}
r=q;
q=q->alp[c];
}
r->isEnd=true;
}
bool search(string s) {
int c;
Node*q=root,*p=root;
for(int i=0;s[i]!='\0';i++) {
c=s[i]-'a';
if(!q->alp[c])
return false;
p=q;
q=q->alp[c];
}
return p->isEnd;
}
};
int main() {
TrieTree t;
t.insert(string("a"));
t.insert(string("the"));
t.insert(string("there"));
t.insert(string("their"));
t.insert(string("answer"));
t.insert(string("any"));
t.insert(string("by"));
cout<<t.search(string("an"))<<endl;
return 0;
}