-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrie.cpp
More file actions
66 lines (60 loc) · 948 Bytes
/
trie.cpp
File metadata and controls
66 lines (60 loc) · 948 Bytes
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
64
65
66
#include<iostream>
#define N 26
using namespace std;
struct node{
node *kids[N];
bool isLeaf;
};
node *create()
{
node *t = new node;
for(int i=0;i<N;i++)
t->kids[i] = NULL;
t->isLeaf = false;
}
node* insert(node *root,string s)
{
if(!root)
{
root = create();
}
node *crawl = root;
for(int i=0;i<s.length();++i)
{
int idx = int(s[i]-'a');
if(!crawl->kids[idx])
crawl->kids[idx] = create();
crawl = crawl->kids[idx];
}
crawl->isLeaf = true;
return root;
}
bool search(node *root,string s)
{
if(!root)return false;
node *crawl = root;
for(int i=0;i<s.length();++i)
{
int idx = int(s[i]-'a');
if(!crawl->kids[idx])
return false;
crawl = crawl->kids[idx];
}
//prefix
return crawl;
//whole word
return (crawl && crawl->isLeaf);
}
main()
{
node * root = NULL;
string s[] = {"hello","hey","how","hi"};
int n = 4;
for(int i=0;i<n;i++)
root = insert(root,s[i]);
string word = "he";
if(search(root,word))
cout<<"\nFound!";
else
cout<<"\nNot found!";
}