forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0211-design-add-and-search-words-data-structure.c
86 lines (74 loc) · 1.97 KB
/
0211-design-add-and-search-words-data-structure.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
typedef struct WordDictionary{
struct WordDictionary *c[26];
bool isWord;
} WordDictionary;
WordDictionary *NewDictionary() {
// allocate and init the memory for a dictionary element.
WordDictionary *n = (WordDictionary*)calloc(1, sizeof(WordDictionary));
return n;
}
WordDictionary* wordDictionaryCreate() {
WordDictionary *root = NewDictionary();
return root;
}
void wordDictionaryAddWord(WordDictionary* obj, char * word) {
assert(obj);
int n = strlen(word);
WordDictionary* dict = obj;
int i, j;
for (i = 0; i < n; i++) {
j = word[i] - 'a';
if (!dict->c[j]) {
dict->c[j] = NewDictionary();
}
dict = dict->c[j];
}
dict->isWord = true;
}
bool wordDictionarySearchR(WordDictionary* dict, char * word, int index) {
assert(dict);
char c = word[index];
int i, j;
if (index == strlen(word)) {
return dict->isWord;
}
if (c == '.') {
for (i = 0; i < 26; i++) {
if (dict->c[i] && wordDictionarySearchR(dict->c[i], word, index + 1)) {
return true;
}
}
} else {
j = c - 'a';
if (!dict->c[j]) {
return false;
}
return wordDictionarySearchR(dict->c[j], word, index + 1);
}
return false;
}
bool wordDictionarySearch(WordDictionary* obj, char * word) {
assert(obj);
return wordDictionarySearchR(obj, word, 0);
}
void wordDictionaryFreeR(WordDictionary* dict) {
assert(dict);
int i;
for (i = 0; i < 26; i++) {
if (dict->c[i]) {
wordDictionaryFreeR(dict->c[i]);
}
}
free(dict);
}
void wordDictionaryFree(WordDictionary* obj) {
assert(obj);
wordDictionaryFreeR(obj);
}
/**
* Your WordDictionary struct will be instantiated and called as such:
* WordDictionary* obj = wordDictionaryCreate();
* wordDictionaryAddWord(obj, word);
* bool param_2 = wordDictionarySearch(obj, word);
* wordDictionaryFree(obj);
*/