-
Notifications
You must be signed in to change notification settings - Fork 0
/
trie.cpp
92 lines (70 loc) · 2.01 KB
/
trie.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
88
89
90
91
92
/** implementation of a trie **/
#include <iostream>
#include <string>
#include <vector>
#define ALPHABET_SIZE 26
using namespace std;
class Trie {
class Trie* children[26];
bool isEnd;
public:
Trie()
{
for(int i=0;i<26;i++)
children[i]=NULL;
isEnd=false;
}
/**insert words into the trie **/
void insert(string word)
{
Trie* curr=this;
for(int i=0;i<word.length();i++)
{
int offset=word[i]-'a';
if(!curr->children[offset])
curr->children[offset]=new Trie();
curr=curr->children[offset];
}
curr->isEnd=true;
}
/** Returns if the word is in the trie. */
bool search(string word)
{
Trie* curr=this;
for(int i=0;i<word.length();i++)
{
int offset=word[i]-'a';
if(curr->children[offset]==NULL)
return false;
curr=curr->children[offset];
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
Trie* curr=this;
for(int i=0;i<prefix.length();i++)
{
int offset=word[i]-'a';
if(!curr->children[offset])
return false;
curr=curr->children[offset];
}
return true;
}
};
int main()
{
string keys[] = {"the", "a", "there",
"answer", "any", "by",
"bye", "their" };
int n = sizeof(keys)/sizeof(keys[0]);
struct Trie *root = new Trie();
// Construct trie
for (int i = 0; i < n; i++)
root->insert(root, keys[i]);
// Search for different keys
root->search(root, "the")? cout << "Yes\n" :
cout << "No\n";
root->search(root, "these")? cout << "Yes\n" :
cout << "No\n";
return 0;
}