LeetCodeTrie字典树

16 篇文章 0 订阅

基础:通过树的结构实现一个进行字符串反复查询的结构:

相关教程:https://leetcode-cn.com/problems/short-encoding-of-words/solution/99-java-trie-tu-xie-gong-lue-bao-jiao-bao-hui-by-s/

208. 实现 Trie (前缀树) https://leetcode-cn.com/problems/implement-trie-prefix-tree/




typedef struct Trie{
    struct Trie * children[26];
    int isEnd;
    
} Trie;

/** Initialize your data structure here. */

Trie* trieCreate() {
    Trie *node = (Trie *)malloc(sizeof(Trie));
    memset(node->children, 0, sizeof(node->children));
    node->isEnd = false;
    return node;
}

/** Inserts a word into the trie. */
void trieInsert(Trie* obj, char * word) {
    int len = strlen(word);
    for (int i = 0;i < len;++i) {
        int ch = word[i] - 'a';
        if (obj->children[ch] == NULL) {
            obj->children[ch] = trieCreate();
        }
        obj = obj->children[ch];
    }
    obj->isEnd = true;
}

/** Returns if the word is in the trie. */
bool trieSearch(Trie* obj, char * word) {
    int len = strlen(word);
    for (int i = 0;i < len;++i) {
        int ch = word[i] - 'a';
        if (obj->children[ch] == NULL) {
            return false;
        }
        obj = obj->children[ch];
    }
    return obj->isEnd;
}

/** Returns if there is any word in the trie that starts with the given prefix. */
bool trieStartsWith(Trie* obj, char * prefix) {
    int len = strlen(prefix);
    for (int i = 0;i < len;++i) {
        int ch = prefix[i] - 'a';
        if (obj->children[ch] == NULL) {
            return false;
        }
        obj = obj->children[ch];
    }
    return true;
}

void trieFree(Trie* obj) {
    for (int i = 0;i < 26;++i) {
        if (obj->children[i] != NULL) {
            trieFree(obj->children[i]);
        }
    }
    free(obj);
}

/**
 * Your Trie struct will be instantiated and called as such:
 * Trie* obj = trieCreate();
 * trieInsert(obj, word);
 
 * bool param_2 = trieSearch(obj, word);
 
 * bool param_3 = trieStartsWith(obj, prefix);
 
 * trieFree(obj);
*/

相关练习:

648. 单词替换 https://leetcode-cn.com/problems/replace-words/

820. 单词的压缩编码 https://leetcode-cn.com/problems/short-encoding-of-words/

677. 键值映射 https://leetcode-cn.com/problems/map-sum-pairs/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值