-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTrie(DS).cpp
87 lines (69 loc) · 1.49 KB
/
Trie(DS).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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include<iostream>
#include<vector>
#include<map>
#include<algorithm>
using namespace std;
struct Trie {
Trie * children[10];
bool end;
};
Trie *root;
Trie* createNode( ){
Trie * x= new Trie() ;
for(int i=0;i<10;i++){
x->children[i] = NULL;
}
x->end = false;
return x;
}
bool search(string s){
if(root==NULL){
return false;
}
Trie *curr = root;
// 913
for( int i=0;i<s.length(); i++ ){
char ch = s[i];
int index = ch - '0' ;// '3'-'0' -> 3
if( curr -> children[index] == NULL ){
return false;
}
curr = curr -> children[index];
}
if ( curr!=NULL && curr->end == true) {
return true ;
}
else {
return false;
}
}
void insert(string s){
if(root==NULL){
root = createNode();
}
Trie *curr = root;
// 913
for( int i=0;i<s.length(); i++ ){
char ch = s[i];
int index = ch - '0' ;// '3'-'0' -> 3
if( curr -> children[index] ==NULL ){
curr -> children[index] = createNode();
}else{
//nothing to be done;
}
curr = curr -> children[index];
}
curr->end = true;
}
int main(){
string s[] = {"9876543210","9876543211","9876543213"};
for(int i=0;i<3;i++){
insert(s[i]);
}
cout<<"checking 9876543213 found : "<<search("9876543213")<<endl;
cout<<"checking 4327823487 found : "<<search("4327823487")<<endl;
cout<<"checking 9876543210 found : "<<search("9876543210")<<endl;
// save
//rocket,batman, mouse, touchmad, hasmap
return 0;
}