第73天(中等题 数据结构)

打卡第七十三天
2道中等题
image

题目:
image

Trie Tree 的实现:
image
image
image
image
image

性质:
image

代码:

class Trie {
private:
    bool isEnd;
    Trie* next[26];
public:
    Trie() {
        isEnd = false;
        memset(next, 0, sizeof(next));// 将所有子节点指针初始化为NULL
    }
    
    void insert(string word) {//向 Trie 中插入一个单词 word
        Trie* node = this;
        for (char c : word) {
            if (node->next[c-'a'] == NULL) {
                node->next[c-'a'] = new Trie();
            }
            node = node->next[c-'a'];
        }
        node->isEnd = true;
    }
    
    bool search(string word) {//查找 Trie 中是否存在单词 word
        Trie* node = this;
        for (char c : word) {
            node = node->next[c - 'a'];
            if (node == NULL) {
                return false;
            }
        }
        return node->isEnd;
    }
    
    bool startsWith(string prefix) {//判断 Trie 中是或有以 prefix 为前缀的单词
        Trie* node = this;
        for (char c : prefix) {
            node = node->next[c-'a'];
            if (node == NULL) {
                return false;
            }
        }
        return true;
    }
};

耗时≈一小时 明天继续

posted @ 2026-01-01 23:38  Wy0518  阅读(2)  评论(0)    收藏  举报