前缀树实现字典添加查询

. - 力扣(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);
 */
相关推荐
weixin_537590456 分钟前
【任务6.13】计算肇事汽车号码
c++·算法·汽车
从今天开始学习Verilog15 分钟前
FFT算法实现之fft IP核
算法·fpga开发
两颗泡腾片28 分钟前
黑马程序员C++核心编程笔记--类和对象--运算符重载
c++·笔记
用户6869161349031 分钟前
1999年NOIP普及组旅行家的预算(洛谷P1016):贪心算法实战指南
c++
程序员编程指南1 小时前
Qt 与 WebService 交互开发
c语言·开发语言·c++·qt·交互
荼蘼1 小时前
基于 KNN 算法的手写数字识别项目实践
人工智能·算法·机器学习
溟洵1 小时前
Qt 窗口 工具栏QToolBar、状态栏StatusBar
开发语言·前端·数据库·c++·后端·qt
Yuroo zhou2 小时前
IMU的精度对无人机姿态控制意味着什么?
单片机·嵌入式硬件·算法·无人机·嵌入式实时数据库
铭哥的编程日记2 小时前
《C++ list 完全指南:list的模拟实现》
c++
程序员编程指南2 小时前
Qt 远程过程调用(RPC)实现方案
c语言·c++·qt·rpc·系统架构