-
Notifications
You must be signed in to change notification settings - Fork 27
/
211. Add and Search Word - Data structure design.c
118 lines (98 loc) · 2.79 KB
/
211. Add and Search Word - Data structure design.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
/*
211. Add and Search Word - Data structure design
Design a data structure that supports the following two operations:
void addWord(word)
bool search(word)
search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.
For example:
addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true
Note:
You may assume that all words are consist of lowercase letters a-z.
click to show hint.
You should be familiar with how a Trie works. If not, please work on this problem: Implement Trie (Prefix Tree) first.
*/
typedef struct dict_s {
int is_leaf;
struct dict_s *child[26];
} WordDictionary;
/** Initialize your data structure here. */
WordDictionary* wordDictionaryCreate() {
WordDictionary *obj;
obj = calloc(1, sizeof(WordDictionary));
//assert(obj);
return obj;
}
/** Adds a word into the data structure. */
void wordDictionaryAddWord(WordDictionary* obj, char* word) {
int k;
if (!word || !*word) return;
while (*word) {
k = *word - 'a';
if (!obj->child[k]) {
obj->child[k] = calloc(1, sizeof(WordDictionary));
//assert(obj->child[k]);
}
obj = obj->child[k];
word ++;
}
obj->is_leaf = 1;
}
/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
bool wordDictionarySearch(WordDictionary* obj, char* word) {
int k;
while (obj && *word) {
if (*word == '.') {
for (k = 0; k < 26; k ++) {
if (wordDictionarySearch(obj->child[k], word + 1)) {
return true;
}
}
return false;
} else {
k = *word - 'a';
obj = obj->child[k];
word ++;
}
}
return (obj && obj->is_leaf) ? true : false;
}
void wordDictionaryFree(WordDictionary* obj) {
int i;
for (i = 0; i < 26; i ++) {
if (obj->child[i]) wordDictionaryFree(obj->child[i]);
}
free(obj);
}
/**
* Your WordDictionary struct will be instantiated and called as such:
* struct WordDictionary* obj = wordDictionaryCreate();
* wordDictionaryAddWord(obj, word);
* bool param_2 = wordDictionarySearch(obj, word);
* wordDictionaryFree(obj);
*/
/*
Difficulty:Medium
Total Accepted:56.8K
Total Submissions:249.4K
Companies Facebook
Related Topics Backtracking Trie Design
Similar Questions
Implement Trie (Prefix Tree)
*/