LeetCode Add and Search Word - Data structure design

题目
这里写图片描述

思路
前缀树,之前有一道LeetCode的题差不多的,我用之前的代码修改了一下即过。

代码

struct WordDictionary {
    char c;
    // sons for "abcdefghijklmnopqrstuvwxyz\0"
    struct WordDictionary * son[27];  
};

/** Initialize your data structure here. */
struct WordDictionary* wordDictionaryCreate() {
    struct WordDictionary * WordDictionary = 
        (struct WordDictionary*)malloc(sizeof(struct WordDictionary));
    WordDictionary->c = '\0';
    memset(WordDictionary->son, 0, sizeof(WordDictionary->son));
    return WordDictionary;
}

/** Inserts a word into the data structure. */
void addWord(struct WordDictionary * wordDictionary, char * word) {
    if (*word == '\0') {
        wordDictionary->son[26] = wordDictionaryCreate();
        // notice that '\0' is important. 
        // There's "abc\0" in Trie doesn't mean there's a word "ab\0".
        wordDictionary->son[26]->c = '\0';  
        return;
    }
    if (wordDictionary->son[*word - 'a'] == NULL) {
        wordDictionary->son[*word - 'a'] = wordDictionaryCreate();
        wordDictionary->son[*word - 'a']->c = *word;
        addWord(wordDictionary->son[*word - 'a'], word + 1);
    }
    else {
        addWord(wordDictionary->son[*word - 'a'], word + 1);
    }
}

/** Returns if the word is in the data structure. A word could
contain the dot character '.' to represent any one letter. */
bool search(struct WordDictionary * wordDictionary, char * word) {
    if (*word == '\0') {
        if (wordDictionary->son[26] != NULL) return true;
        else return false;
    }
    if (*word == '.') {
        for (int i = 0; i < 26; i++) {
            if (wordDictionary->son[i] != NULL) {
                if (search(wordDictionary->son[i], word + 1))
                    return true;
            }
        }
    }
    else {
        if (wordDictionary->son[*word - 'a'] == NULL) {
            return false;
        }
        else {
            return search(wordDictionary->son[*word - 'a'], word + 1);
        }
    }
}

/** Deallocates memory previously allocated for the data structure. */
void wordDictionaryFree(struct WordDictionary * wordDictionary) {
    if (wordDictionary != NULL) {
        for (int i = 0; i < 26; i++) {
            wordDictionaryFree(wordDictionary->son[i]);
        }
        free(wordDictionary);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值