首页 > 其他分享 >208. 实现 Trie (前缀树)

208. 实现 Trie (前缀树)

时间:2023-09-25 15:35:55浏览次数:19  
标签:node search word 前缀 Trie 208 app next

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

代码


class Trie {
private:
    bool isEnd;
    Trie* next[26];
public:
    Trie() {
        isEnd = false;
        memset(next,0,sizeof(next));
    }
    
    void insert(string word) {
        Trie* node = this;
        for(char c : word){
            if(node->next[c - 'a'] == nullptr){
                node->next[c - 'a'] = new Trie();
            }
            node = node->next[c - 'a'];
        }
        node->isEnd = true;
    }
    
    bool search(string word) {
        Trie* node = this;
        for(char c : word){
            if(node->next[c - 'a'] == nullptr){
                return false;
            }
            node = node->next[c - 'a'];
        }
        if(node->isEnd){
            return true;
        }
        else{
            return false;
        }
    }
    
    bool startsWith(string prefix) {
        Trie* node = this;
        for(char c : prefix){
            if(node->next[c - 'a'] == nullptr){
                return false;
            }
            node = node->next[c - 'a'];
        }
        return true;
    }
};

标签:node,search,word,前缀,Trie,208,app,next
From: https://www.cnblogs.com/lihaoxiang/p/17728024.html

相关文章

  • Trie字典
    Trie树,又叫字典树,前缀树(PrefixTree),单词查找树,是一种多叉树的结构.{"a","apple","appeal","appear","bee","beef","cat"}深色表示接受态关键字集合{"pool","prize","prepare","preview&......
  • 2023.9.24 lx2080 Serdes Config
    //sedesprotocolconfiguration:ubootnoprintinfo[lx2160a]bootfailwhenSRDS_PRTCL_S2=10-NXPCommunity //sys_clock与ref_clock:系统时钟内部提供;外部参考时钟可以根据外设的频率需求设计......
  • Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connect
    报错 Maxretriesexceededwithurl:/(CausedbyNewConnectionError('<urllib3.connection.HTTPSConnectionobjectat0x000001A73833FD00>:Failedtoestablishanewconnection:[WinError10060]  pipuninstallrequestsurllib3  #先卸载pipinstallre......
  • 高维前缀和
    考虑高维前缀和,可以把每一维前缀和比如:三维前缀和for(i=1;i<=a;i++) for(j=1;j<=b;j++) for(k=1;k<=c;k++) f[i][j][k]+=f[i-1][j][k];for(i=1;i<=a;i++) for(j=1;j<=b;j++) for(k=1;k<=c;k++) f[i][j][k]+=f[i][j-1][k];for(i=1;i<=a;i++)......
  • 前缀树
    classTrieNode{public:intpass;intend;vector<TrieNode*>nexts;TrieNode(){pass=0;end=0;for(inti=0;i<26;i++)nexts.push_back(nullptr);}};classTrie{public:TrieNode......
  • 基本前缀和算法:一维前缀和、二维前缀和、子矩阵和
    1、一维前缀和以AcWing.795为例,题目要求如下:输入一个长度为N的整数序列。接下来再输入m个询问,每个询问输入一对l,r。对于每个询问,输出原序列中从第l个数到第r个数的和。输入格式第一行包含两个整数n和m。第二行包含n个整数,表示整数数列。接下来m行,每行包含两个整数l和r,表示一......
  • 力扣14.最长公共前缀
    编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串 ""。 示例1:输入:strs=["flower","flow","flight"]输出:"fl" 示例2:输入:strs=["dog","racecar","car"]输出:""解释:输入不存在公共前缀。 ......
  • [BCB]E2089 Identifier 'ReadPragram' cannot have a type qualifier
    这些天一直在改程序,今天突然冒出来如下错误:[C++Error]Unit1.cpp(4114):E2089Identifier'ReadPragram'cannothaveatypequalifier[C++Error]Unit1.cpp(6751):E2089Identifier'Button1Click'cannothaveatypequalifier[C++Error]Unit1.cpp(8593):E2139D......
  • windows批量删除指定前缀key
    直接上代码:del_keys_by_prefix.bat@echooffecho调用格式:[redis地址][redis密码][redis库号][待删除的key前缀带*]setkeysfile=redis-cached-keys.txtredis-cli-h%1-a%2-n%3keys%4>%keysfile%FOR/F%%iin(%keysfile%)DO(redis-cli-h%1-a%2-n%3de......
  • abap 中 for all entries in 中的 distinct 功能
    用forallentriesin做查询的时候,能够进行自动的distinct,请看如下的例子:REPORTZ_LJC222.types:beginofty_mm,matnrtypemara-matnr,endofty_mm.types:beginofty_makt,matnrtypemara-matnr,sprastypemakt-spras,......