Skip to content

Commit 5566498

Browse files
committed
AddAndSearchWord.c added
1 parent e915cf5 commit 5566498

File tree

1 file changed

+14
-19
lines changed

1 file changed

+14
-19
lines changed

LuoSonglei/week-94/AddAndSearchWord.c

Lines changed: 14 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ Source : https://leetcode.com/problems/add-and-search-word-data-structure-d
1010
struct TrieNode
1111
{
1212
bool isWord;
13-
struct TrieNode *children[SIZE];
13+
struct TrieNode **children;
1414
};
1515

1616
struct WordDictionary
@@ -20,12 +20,11 @@ struct WordDictionary
2020

2121
struct TrieNode* trieNodeMaker()
2222
{
23-
printf("making a trie node now\n");
2423
struct TrieNode *t = (struct TrieNode*)malloc(sizeof(struct TrieNode));
2524
t->isWord = false;
26-
for(int i = 0; i < SIZE; i++)
27-
t->children[i] = NULL;
28-
printf("return the newly created trie node\n");
25+
int space = sizeof(struct TrieNode*)*SIZE;
26+
t->children = (struct TrieNode**)malloc(space);
27+
memset(t->children, 0, space);
2928
return t;
3029
}
3130
struct WordDictionary* wordDictionaryCreate()
@@ -40,42 +39,38 @@ void addWord(struct WordDictionary* dict, char* word)
4039
struct TrieNode *cur = dict->root;
4140
for(int i = 0; word[i]; i++)
4241
{
43-
printf("inserting: %c\n", word[i]);
4442
if(!(cur->children[word[i]-'a']))
4543
cur->children[word[i]-'a'] = trieNodeMaker();
4644
cur = cur->children[word[i]-'a'];
4745
}
48-
printf("inserting done!\n");
4946
cur->isWord = true;
5047
}
5148

5249

5350
bool trieSearch(const char* word, struct TrieNode* root)
5451
{
55-
printf("searching for %s in dict\n", word);
5652
struct TrieNode *cur = root;
5753
for(int i = 0; word[i]; i++)
5854
{
59-
if(cur && word[i]!='.')
55+
if(!cur) return false;
56+
if(word[i]!='.')
6057
cur = cur->children[word[i]-'a'];
61-
else if(cur && word[i]=='.')
58+
else if(word[i]=='.')
6259
{
63-
struct TrieNode *t = cur;
64-
for(int j = 0; j < SIZE; j++)
65-
{
66-
cur = t->children[i];
67-
if(trieSearch(word+i+1, cur))
60+
for(int j = 0; j < SIZE; j++) //try every possible path;
61+
if(trieSearch(word+i+1, cur->children[j]))
6862
return true;
69-
}
63+
return false; //all possible paths have failed;
7064
}
71-
else break;
7265
}
73-
return cur&&cur->isWord;
66+
return cur&&cur->isWord; //the last checking;
7467
}
7568

76-
//Runtime Error - unkonwn!
69+
//Runtime Error - unkonwn! - pointer of an array -> children;
70+
// The term comes from "retrieval" and the originator, Edward Fredkin, pronounced it "tree." However, "trey" is the more common pronounciation. "Try" is rare and considered incorrect.
7771
//https://leetcode.com/discuss/39022/80ms-clear-c-code-with-detailed-explanations
7872
//https://en.wikipedia.org/wiki/Trie
73+
//AC - 44ms;
7974
bool search(struct WordDictionary* dict, char* word)
8075
{
8176
trieSearch(word, dict->root);

0 commit comments

Comments
 (0)