• Leetcode 208. 实现 Trie (前缀树)


    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 。

    思路:

    实现词典树,并实现插入、查找相同字符串、查找相同前缀的字符串功能。

    不需要输出字符的话就不用记录本身节点的char。

    每个节点保存Trie* next[26]的后续指针。当插入时按照index放入对应next数组中。没有则新建。使用isEnd记录当前节点是否为某个单词的终点。

    查询时按序遍历

    class Trie {
    public:
        Trie() {
            next.resize(26);
            isEnd=false;
        }
        
        void insert(string word) {
            Trie* node=this;
            for(int i=0;i<word.size();++i){
                char c=word[i];
                int index=c-'a';
                if(node->next[index]==nullptr){
                    node->next[index]=new Trie();
                }
                node=node->next[index];
            }
            node->isEnd=true;
        }
        
        bool search(string word) {
            Trie* node=this;
            for(int i=0;i<word.size();++i){
                char c=word[i];
                int index=c-'a';
                if(node->next[index]==nullptr)
                    return false;
                node=node->next[index];
            }
            return node!=nullptr&&node->isEnd;
        }
        
        bool startsWith(string prefix) {
            Trie* node=this;
            for(int i=0;i<prefix.size();++i){
                char c=prefix[i];
                int index=c-'a';
                if(node->next[index]==nullptr)
                    return false;
                node=node->next[index];
            }
            return node!=nullptr;
        }
        vector<Trie*> next;
        bool isEnd;
    };
    
    /**
     * 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);
     */
  • 相关阅读:
    [转] MapReduce详解
    [转] 自然语言处理全家福:纵览当前NLP中的任务、数据、模型与论文
    [转] 一文读懂BERT中的WordPiece
    [转] 文本分类——GLUE数据集介绍
    [转] Transformer详解
    [python] 转json好用的工具mark
    [转] 深度学习中的注意力机制
    [转] Python之time模块的时间戳、时间字符串格式化与转换
    日期相关
    airflow的定时任务
  • 原文地址:https://www.cnblogs.com/zl1991/p/16018005.html
Copyright © 2020-2023  润新知