前缀树实现字典添加查询

. - 力扣(LeetCode)

Trie (发音类似 "try")或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完和拼写检查。

请你实现 Trie 类:

  • Trie() 初始化前缀树对象。
  • void insert(String word) 向前缀树中插入字符串 word
  • boolean search(String word) 如果字符串 word 在前缀树中,返回 true(即,在检索之前已经插入);否则,返回 false
  • boolean startsWith(String prefix) 如果之前已经插入的字符串 word 的前缀之一为 prefix ,返回 true ;否则,返回 false

示例:

复制代码
输入
["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
输出
[null, null, true, false, true, null, true]

解释
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple");   // 返回 True
trie.search("app");     // 返回 False
trie.startsWith("app"); // 返回 True
trie.insert("app");
trie.search("app");     // 返回 True

提示:

  • 1 <= word.length, prefix.length <= 2000
  • wordprefix 仅由小写英文字母组成
  • insertsearchstartsWith 调用次数 总计 不超过 3 * 104
cpp 复制代码
class Trie {
public:
    Trie() {
        childs = std::vector<Trie*>(26, nullptr);
    }

    ~Trie() {
        for (auto child: childs) {
            if (child) {
                delete child;
            }
        }
    }
    
    Trie* searchInternal(string word) {
        auto p = this;
        for (auto ch : word) {
            int idx = ch - 'a';
            if (p->childs[idx] == nullptr) {
                return nullptr;
            }
            p = p->childs[idx];
        }
        return p;
    }

    void insert(string word) {
        auto p = this;
        for (auto ch : word) {
            int idx = ch - 'a';
            if (p->childs[idx] == nullptr) {
                p->childs[idx] = new Trie;
            }
            p = p->childs[idx];
        }
        p->end = true;
    }
    
    bool search(string word) {
        auto tree = searchInternal(word);
        return tree != nullptr && tree->end;
    }
    
    bool startsWith(string prefix) {
        return searchInternal(prefix) != nullptr;
    }

    std::vector<Trie*> childs;
    bool end = false;
};

/**
 * Your Trie object will be instantiated and called as such:
 * Trie* obj = new Trie();
 * obj->insert(word);
 * bool param_2 = obj->search(word);
 * bool param_3 = obj->startsWith(prefix);
 */
相关推荐
澈2072 分钟前
C++面向对象:类与对象核心解析
c++·算法
用户690673881924 分钟前
基于无人机的单目测距系统,平均误差仅2.12%
算法
6Hzlia17 分钟前
【Hot 100 刷题计划】 LeetCode 141. 环形链表 | C++ 哈希表直觉解法
c++·leetcode·链表
dinl_vin20 分钟前
LangChain 系列·(四):RAG 基础——给大模型装上“外脑“
人工智能·算法·langchain
探物 AI1 小时前
【感知·医学分割】当 YOLOv11 杀入医学赛道:先检测后分割的级联架构
算法·yolo·计算机视觉·架构
隔壁大炮1 小时前
Day06-08.CNN概述介绍
人工智能·pytorch·深度学习·算法·计算机视觉·cnn·numpy
白云千载尽1 小时前
前馈与反馈——经典控制理论中的基础概念
人工智能·算法
炽烈小老头1 小时前
【每日天学习一点算法 2026/04/27】缺失的第一个正数
学习·算法
handler011 小时前
Linux 进程探索:从 PCB 管理到 fork() 的写时拷贝
linux·c语言·c++·笔记·学习
南宫萧幕1 小时前
HEV 智能能量管理实战:从 MPC/PPO 理论解析到 Python-Simulink 联合仿真闭环全流程
开发语言·python·算法·matlab·控制