| 
 | 1 | +/*******************************************  | 
 | 2 | +Author      : LHearen  | 
 | 3 | + | 
 | 4 | +Time        : 2016-03-03 10:12  | 
 | 5 | +Description :   | 
 | 6 | +Source      : https://leetcode.com/problems/implement-trie-prefix-tree/  | 
 | 7 | +*******************************************/  | 
 | 8 | +#include <stdlib.h>  | 
 | 9 | +#include <bool.h>  | 
 | 10 | +#define LEN 26  | 
 | 11 | +struct TrieNode  | 
 | 12 | +{  | 
 | 13 | +    bool isWord;  | 
 | 14 | +    struct TrieNode **children;  | 
 | 15 | +};  | 
 | 16 | + | 
 | 17 | +struct TrieNode* nodeMaker()  | 
 | 18 | +{  | 
 | 19 | +    struct TrieNode *t = (struct TrieNode*)malloc(sizeof(struct TrieNode));  | 
 | 20 | +    t->isWord = false;  | 
 | 21 | +    int space = sizeof(struct TrieNode*)*LEN;  | 
 | 22 | +    t->children = (struct TrieNode**)malloc(space);  | 
 | 23 | +    memset(t->children, 0, space);  | 
 | 24 | +    return t;  | 
 | 25 | +}  | 
 | 26 | +struct TrieNode* trieCreate()  | 
 | 27 | +{  | 
 | 28 | +    return nodeMaker();  | 
 | 29 | +}  | 
 | 30 | + | 
 | 31 | +void insert(struct TrieNode *root, char *word)  | 
 | 32 | +{  | 
 | 33 | +    for(int i = 0; word[i]; i++)  | 
 | 34 | +    {  | 
 | 35 | +        if(!(root->children[word[i]-'a']))  | 
 | 36 | +            root->children[word[i]-'a'] = nodeMaker();  | 
 | 37 | +        root = root->children[word[i]-'a'];  | 
 | 38 | +    }  | 
 | 39 | +    root->isWord = true;  | 
 | 40 | +}  | 
 | 41 | + | 
 | 42 | +//AC - 40ms;  | 
 | 43 | +bool search(struct TrieNode *root, char *word)  | 
 | 44 | +{  | 
 | 45 | +    for(int i = 0; word[i]; i++)  | 
 | 46 | +    {  | 
 | 47 | +        root = root->children[word[i]-'a'];  | 
 | 48 | +        if(!root) return false;  | 
 | 49 | +    }  | 
 | 50 | +    return root&&root->isWord;  | 
 | 51 | +}  | 
 | 52 | + | 
 | 53 | +bool startsWith(struct TrieNode *root, char *prefix)  | 
 | 54 | +{  | 
 | 55 | +    for(int i = 0; prefix[i]; i++)  | 
 | 56 | +    {  | 
 | 57 | +        root = root->children[prefix[i]-'a'];  | 
 | 58 | +        if(!root) return false;  | 
 | 59 | +    }  | 
 | 60 | +    return root;  | 
 | 61 | +}  | 
 | 62 | + | 
 | 63 | +void trieFree(struct TrieNode *root)  | 
 | 64 | +{  | 
 | 65 | +    free(root->children);  | 
 | 66 | +    free(root);  | 
 | 67 | +}  | 
0 commit comments