首页 > 其他分享 >TrieTree(字典树)

TrieTree(字典树)

时间:2022-09-24 10:47:37浏览次数:70  
标签:return string TrieNode word int child TrieTree 字典

TrieTree(字典树)


定义

TrieTree,,字典树,又叫前缀树,单词查找树,是一种针对字符串前缀进行维护的数据结构,给定一个字符串集合构建的前缀树,可以在树中查找字符串或者字符串的前缀。

分析

一般情况下,字符串仅有小写字母构成,以下分析仅考虑包含小写字母的字符串,前缀树每个节点最多有26个子树,从根节点开始,向下延伸的每条路径代表一个字符(a~z),通过字典集合可以构建出整个前缀树,以[them, zip, team, the, app, that] 为例,前缀树如下图:

在前缀树中,终端叶子节点均为有效节点,针对不同问题可能保存着不同的val值。

具体实现

数据结构

class TrieTree {
private:
    struct TrieNode {
        bool val = false;
        TrieNode *child[26];
    };
    TrieNode root;
public:
    TrieTree() {
        root = new TrieNode();
    }
    void insert(string &word);
    bool search(string &word)
}

建树

void insert(string &word) {
    TrieNode *p = root;
    for(auto k : word) {
        int index = int(k - 'a');
        if(p->child[index] = nullptr) {
            p->child[index] = new TrieNode();
        }
        p = p->child[index];
    }
    p->val = true;
}

搜索

bool search(string &word) {
    TrieNode *p = root;
    for(auto k : word) {
        int index  = int(k - 'a');
        if(p->child[index] == nullptr) return false;
        p = p->child[index];
    }
    return p->val;
}

字典树相关问题

单词替换

题目描述

在英语中,我们有一个叫做 词根(root) 的概念,可以词根后面添加其他一些词组成另一个较长的单词——我们称这个词为 继承词(successor)。例如,词根an,跟随着单词 other(其他),可以形成新的单词 another(另一个)。

现在,给定一个由许多词根组成的词典 dictionary 和一个用空格分隔单词形成的句子 sentence。你需要将句子中的所有继承词用词根替换掉。如果继承词有许多可以形成它的词根,则用最短的词根替换它。

你需要输出替换之后的句子。

示例1

输入:dictionary = ["cat","bat","rat"], sentence = "the cattle was rattled by the battery"
输出:"the cat was rat by the bat"

示例2

输入:dictionary = ["a","b","c"], sentence = "aadsfasf absbs bbab cadsfafs"
输出:"a a b c"

Solution

以词根构建字典树,这题实际就是在一组单词种对每个单词查找其在字典中的最短前缀,并替换。

Code

class Solution {
private:
    struct TrieNode {
        bool val;
        TrieNode *child[26];
    };
    TrieNode *root = new TrieNode();
public:
    vector<string> split(string &str, char d) {
        vector<string> ans;
        string temp = "";
        for(auto k : str) {
            if(k == d) {
                ans.push_back(temp);
                temp = "";
                continue;
            }
            temp += k;
        }
        if(temp != "") ans.push_back(temp);
        return ans;
    }

    string replaceWords(vector<string>& dictionary, string sentence) {
        root = new TrieNode();
        for(auto k : dictionary) {
            insert(k);
        }
        vector<string> sq = split(sentence, ' ');
        string out = "";
        for(auto k : sq) {
            string prefix = shortPrefix(k);
            if(out != "") out += " ";
            if(prefix == "") out += k;
            else out += prefix;
        }
        return out;
    }

    void insert(string &prefix) {
        TrieNode *p = root;
        for(int i = 0; i < prefix.length(); ++i) {
            int k = int(prefix[i] - 'a');
            if(p->child[k] == nullptr) p->child[k] = new TrieNode();
            p = p->child[k];
        }
        p->val = true;
        return;
    }

    string shortPrefix(string &word) {
        string ans = "";
        TrieNode *p = root;
        for(int i = 0; i < word.length(); ++i) {
            int k = int(word[i] - 'a');
            if(p->child[k] == nullptr) {
                if(p->val) return ans;
                else return "";
            }
            if(p->val) return ans;
            ans += word[i];
            p = p->child[k];
        }
        if(p->val) return ans;
        return "";
    }
};

标签:return,string,TrieNode,word,int,child,TrieTree,字典
From: https://www.cnblogs.com/LeafLove/p/16725076.html

相关文章

  • Trie树(字典树,前缀树)
    Trie中文名又叫做字典树,前缀树等,因为其结构独有的特点,经常被用来统计,排序,和保存大量的字符串,经常见于搜索提示,输入法文字关联等,当输入一个值,可以自动搜索出可能的选择。当......
  • 在Winform开发中,我们使用的几种下拉列表展示字典数据的方式
    在Winform开发中中,我们为了方便客户选择,往往使用系统的字典数据选择,毕竟选择总比输入来的快捷、统一,一般我们都会简单封装一下,以便方便对控件的字典值进行展示处理,本篇随笔......
  • 字典树-2416. 字符串的前缀分数和
    问题描述给你一个长度为n的数组words,该数组由非空字符串组成。定义字符串word的分数等于以word作为前缀的words[i]的数目。例如,如果words=["a","ab......
  • 复习元组列表字典
    元组能存储多个不同类型的数据,且是有序的。但它是不可变的,因此不能进行修改、删除或添加元素的操作。列表和元组非常相似,唯一的不同是列表的元素是可以修改的。字典的元素......
  • 字典
    字典-定义:在Python中,将两种数据关联在一起形成一个元素,由多个这样的元素组成的数据类型称为字典,又称为dict。字典中的元素是不考虑排列顺序的。组成字典元素(item)的两个......
  • Python在字典中通过键名查找键值
    deffind(target,dict_data):""":paramtarget:需要查找的键名:paramdict_data:需要查找的列表:return:如果找到就返回对应键名的键值,否则提示没......
  • 字典增删改查
    #字典Dict,也称为mapping字典是可变的、无序的、key不重复的key-value键值对集合初始化:dict(**kwargs)使用name=value对初始化一个字典dict(iterable,**kwarg),使用可迭代......
  • 洛谷真题字典树
    P8306【模板】字典树1#include<bits/stdc++.h>2usingnamespacestd;3intt,n,q;4constintmaxn=3000005;5chars[maxn];6intson[maxn][80],cnt[ma......
  • Day_1(并查集朋友圈、字典序排序)
    1.并查集朋友圈:找出最多的一个圈子内有多少用户!id[](表示当前节点的父节点)nodeNum[](表示当前节点为根的那一组节点数量)importjava.util.Scanner;//并查集class......
  • python数据类型之字典Dictionary
    1.python字典字典(dictionary)是除列表以外python之中最灵活的内置数据结构类型。列表是有序的对象集合,字典是无序的对象集合。两者之间的区别在于:字典当中的元素是通过......