您好,欢迎来到伴沃教育。
搜索
您的当前位置:首页力扣每日一题208:实现 Trie (前缀树)

力扣每日一题208:实现 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
  • word 和 prefix 仅由小写英文字母组成
  • insertsearch 和 startsWith 调用次数 总计 不超过 3 * 104 次

面试中遇到过这道题?

1/5

通过次数

326.7K

提交次数

4K

通过率

72.0%

题目提供的结构(c++)

class Trie {
public:
    Trie() {

    }
    
    void insert(string word) {

    }
    
    bool search(string word) {

    }
    
    bool startsWith(string prefix) {

    }
};

/**
 * 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);
 */

思路

首先很多人还不知道前缀树。

简单说来就是,根节点不存放数据,其它节点每个节点存放一个字母。从根节点到某个节点形成的路径就是一个单词。每一个非根节点会有个标记,记录以该节点为尾的路径是不是一个单词。

int n=word.length();
Node* cur=root;
int i=0;
while( i<n&&(cur->child).find(word[i])!=(cur->child).end() ){
    cur=(cur->child)[word[i]];
    i++;
}

复杂度
时间复杂度:

添加和查找时间复杂度,: O(m)O(m)O(m)
其中m为word的长度
查找前缀的时间复杂度: O(p)O(p)O(p)
p为前缀的长度

空间复杂度:

空间复杂度为单词的总长度: O(numberofwords∗averagewordlength)

实现代码

class Trie {
public:
    struct Node{
        bool flag=false;        //结束标志,true代表是结束
        char letter;         //该节点代表的字母
        unordered_map<char,Node*> child;
        string val;         //根走到当前节点的值
        Node() {};
        Node(char c) : letter(c) {};
    };
    Node* root;
    Trie() {
        root=new Node('#');
    }
    
    void insert(string word) {
        int n=word.length();
        Node* cur=root;
        int i=0;
        while( i<n&&(cur->child).find(word[i])!=(cur->child).end() ){
            cur=(cur->child)[word[i]];
            i++;
        }
        //word已经存在的情况
        if(i==n&&(cur->flag)==true){
            return;
        }else if(i==n&&(cur->flag)==false){
            //word在前缀树中但是不存在的情况
            cur->flag=true;
        }else if(i!=n){
            while(i<n){
                (cur->child)[word[i]]=new Node(word[i]);
                cur=(cur->child)[word[i]];
                i++;
            }
            (cur->flag)=true;//标志结束
        }
        //
    }
    
    bool search(string word) {
        int n=word.length();
        int i=0;            //word中最后一个匹配成功的后一个位置
        Node* cur=root;     //前缀树中匹配成功的最后一个位置
        while( i<n&&(cur->child).find(word[i])!=(cur->child).end() ){
            cur=(cur->child)[word[i]];
            i++;
        }
        if(i==n&&(cur->flag)==true ) return true;
        else return false;
    }
    
    bool startsWith(string prefix) {
        int n=prefix.length();
        int i=0;
        Node* cur=root;
        while( i<n&&(cur->child).find(prefix[i])!=(cur->child).end() ){
            cur=(cur->child)[prefix[i]];
            i++;
        }
        if( i==n&&(cur->flag==true||(cur->child).size()!=0) ) return true;
        else return 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);
 */

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- bangwoyixia.com 版权所有 湘ICP备2023022004号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务