forked from iamAnki/Codes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrie Implementation.cpp
More file actions
102 lines (87 loc) · 1.83 KB
/
Trie Implementation.cpp
File metadata and controls
102 lines (87 loc) · 1.83 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
// contributed by Ayush Akash
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <algorithm>
using namespace std;
struct node
{
int prefix_count;
bool isEnd;
struct node *child[26];
}*head;
void init()
{
head = new node();
head->isEnd = false;
head->prefix_count = 0;
}
void insert(string word)
{
node *current = head;
current->prefix_count++;
for(int i = 0 ; i < word.length(); ++i)
{
int letter = (int)word[i] - (int)'a'; //extrct first character of word
if(current->child[letter] == NULL)
current->child[letter] = new node();
current->child[letter]->prefix_count++;
current = current->child[letter];
}
current->isEnd = true;
}
bool search(string word)
{
node *current = head;
for(int i = 0 ; i < word.length(); ++i)
{
int letter = (int)word[i] - (int)'a';
if(current->child[letter] == NULL)
return false; //not found
current = current->child[letter];
}
return current->isEnd;
}
int words_with_prefix(string prefix)
{
node *current = head;
for(int i = 0; i < prefix.length() ; ++i)
{
int letter = (int)prefix[i] - (int)'a';
if(current->child[letter] == NULL)
return 0;
else
current = current->child[letter];
}
return current->prefix_count;
}
int main()
{
init();
string s = "chandan";
insert(s);
s = "mittal";
insert(s);
s = "chirag";
insert(s);
s = "shashank";
insert(s);
s = "abhinav";
insert(s);
s = "arun";
insert(s);
s = "abhishek";
insert(s);
if(search("chandan"))
printf("found chandan\n");
if(search("arun"))
printf("found arun\n");
if(search("abhi"))
printf("found abhi\n");
else
printf("not found abhi\n");
printf("no of words with prefix abhi are %d\n",words_with_prefix("abhi"));
printf("no of words with prefix ch are %d\n",words_with_prefix("ch"));
printf("no of words with prefix k are %d\n ",words_with_prefix("k"));
return 0;
}