-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathTrie_class.hpp
84 lines (74 loc) · 1.34 KB
/
Trie_class.hpp
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
#ifndef _TRIE_HPP
#define _TRIE_HPP
class Node
{
public:
Node *add[56];
int key;
Node()
{ // constructor
key = -1;
for (int i = 0; i < 56; i++)
add[i] = NULL;
}
Node *getNode()
{ // returns a ptr to a new node
Node *temp;
temp = new Node;
return temp;
}
};
class Trie
{
private:
Node *start;
public:
Trie()
{ // default constructor for class Trie
Node temp;
start = temp.getNode();
}
void insert(std::string s, int k)
{
Node *ptr = start; // Setting the root as the first letter of the word
Node temp;
for (int i = 0; i < s.length(); i++)
{
int next = Trie::getNext(s[i]);
if (ptr->add[next] == NULL)
ptr->add[next] = temp.getNode(); // if next index doesn't exist we'll create a new Node
ptr = ptr->add[next];
}
ptr->key = k;
}
int search(std::string s)
{
Node *ptr = start;
for (int i = 0; i < s.length(); i++)
{
int next = Trie::getNext(s[i]);
if (ptr->add[next] == NULL)
{
return -1;
}
ptr = ptr->add[next];
}
return ptr->key;
}
int getNext(char c)
{
if (c >= 'a' && c <= 'z')
return c - 'a';
if (c >= 'A' && c <= 'Z')
return c - 'A' + 26;
if (c == ' ')
return 52;
if (c == '-')
return 53;
if (c == ',')
return 54;
if (c == '.')
return 55;
}
};
#endif