力扣每日一题208:实现 Trie (前缀树)

题目内容

难度 中等

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

提交次数

454K

通过率

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++;
}

上述代码走完后 :
i会指向word中最后一个匹配成功的后一个位置
cur会指向前缀树中最后一个匹配成功的地址。
随后就很方便的进行插入,查找,找到前缀操作。

复杂度
时间复杂度:

添加和查找时间复杂度,: 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);
 */

  • 13
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值