-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtry.c
133 lines (117 loc) · 2.21 KB
/
try.c
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct TrieNode {
int isleaf;
char value;
struct TrieNode* children[26];
};
/** Initialize your data structure here. */
struct TrieNode* trieCreate() {
struct TrieNode* root=(struct TrieNode*)malloc(sizeof(struct TrieNode));
root->value=':';
int i;
for(i=0;i<26;i++)
{
root->children[i]=NULL;
}
return root;
}
/** Inserts a word into the trie. */
void insert(struct TrieNode* temp, char* str) {
int i=0;
while(i<strlen(str) && temp!=NULL)
{
int index=str[i]-'a';
if(temp->children[index]==NULL)
{
temp->children[index]=(struct TrieNode*)malloc(sizeof(struct TrieNode));
temp->children[index]->value=str[i];
if(i==strlen(str)-1)
{
temp->children[index]->isleaf=1;
}
else
{
temp->children[index]->isleaf=0;
}
i++;
temp=temp->children[index];
}
else
{
i++;
temp=temp->children[index];
}
}
}
/** Returns if the word is in the trie. */
int search(struct TrieNode* root, char* str) {
int i=0;
while(i<strlen(str) && root!=NULL)
{
int index=str[i]-'a';
if(root->children[index]==NULL)
{
return 0;
}
else
{
i++;
if(i==strlen(str) && root->children[index]->isleaf==0)
{
return 0;
}
root=root->children[index];
}
}
if(i<strlen(str))
return 0;
return 1;
}
/** Returns if there is any word in the trie
that starts with the given prefix. */
int startsWith(struct TrieNode* root, char* prefix) {
int i=0;
while(i<strlen(prefix) && root!=NULL)
{
int index=prefix[i]-'a';
if(root->children[index]==NULL)
{
return 0;
}
else
{
i++;
root=root->children[index];
}
}
if(i<strlen(prefix))
{
// printf("gg");
return 0;
}
return 1;
}
/** Deallocates memory previously allocated for the TrieNode. */
void trieFree(struct TrieNode* root) {
if(root!=NULL)
{
int i;
for(i=0;i<26;i++)
{
trieFree(root->children[i]);
}
free(root);
}
}
int main()
{
// Your Trie object will be instantiated and called as such:
struct TrieNode* node = trieCreate();
insert(node, "ab");
printf("%d",search(node, "a"));
printf("%d",startsWith(node,"a"));
// trieFree(node);
return 0;
}