Skip to content

Commit d581481

Browse files
authored
Merge pull request #2171 from seinlin/211
Add 0211-design-add-and-search-words-data-structure.c
2 parents 836eda3 + 3fd9070 commit d581481

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
typedef struct WordDictionary{
2+
struct WordDictionary *c[26];
3+
bool isWord;
4+
} WordDictionary;
5+
6+
WordDictionary *NewDictionary() {
7+
// allocate and init the memory for a dictionary element.
8+
WordDictionary *n = (WordDictionary*)calloc(1, sizeof(WordDictionary));
9+
return n;
10+
}
11+
12+
WordDictionary* wordDictionaryCreate() {
13+
WordDictionary *root = NewDictionary();
14+
return root;
15+
}
16+
17+
void wordDictionaryAddWord(WordDictionary* obj, char * word) {
18+
assert(obj);
19+
int n = strlen(word);
20+
WordDictionary* dict = obj;
21+
int i, j;
22+
for (i = 0; i < n; i++) {
23+
j = word[i] - 'a';
24+
if (!dict->c[j]) {
25+
dict->c[j] = NewDictionary();
26+
}
27+
dict = dict->c[j];
28+
}
29+
dict->isWord = true;
30+
}
31+
32+
bool wordDictionarySearchR(WordDictionary* dict, char * word, int index) {
33+
assert(dict);
34+
35+
char c = word[index];
36+
int i, j;
37+
if (index == strlen(word)) {
38+
return dict->isWord;
39+
}
40+
if (c == '.') {
41+
for (i = 0; i < 26; i++) {
42+
if (dict->c[i] && wordDictionarySearchR(dict->c[i], word, index + 1)) {
43+
return true;
44+
}
45+
}
46+
} else {
47+
j = c - 'a';
48+
if (!dict->c[j]) {
49+
return false;
50+
}
51+
return wordDictionarySearchR(dict->c[j], word, index + 1);
52+
}
53+
return false;
54+
}
55+
56+
bool wordDictionarySearch(WordDictionary* obj, char * word) {
57+
assert(obj);
58+
return wordDictionarySearchR(obj, word, 0);
59+
}
60+
61+
void wordDictionaryFreeR(WordDictionary* dict) {
62+
assert(dict);
63+
int i;
64+
for (i = 0; i < 26; i++) {
65+
if (dict->c[i]) {
66+
return wordDictionaryFreeR(dict->c[i]);
67+
}
68+
}
69+
free(dict);
70+
}
71+
72+
void wordDictionaryFree(WordDictionary* obj) {
73+
assert(obj);
74+
wordDictionaryFreeR(obj);
75+
}
76+
77+
/**
78+
* Your WordDictionary struct will be instantiated and called as such:
79+
* WordDictionary* obj = wordDictionaryCreate();
80+
* wordDictionaryAddWord(obj, word);
81+
82+
* bool param_2 = wordDictionarySearch(obj, word);
83+
84+
* wordDictionaryFree(obj);
85+
*/
86+

0 commit comments

Comments
 (0)