zoukankan      html  css  js  c++  java
  • 【LeetCode-树】实现 Trie (前缀树)

    题目描述

    实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。
    示例:

    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
    

    题目链接: https://leetcode-cn.com/problems/implement-trie-prefix-tree/

    思路

    Trie 树每个节点存储数组,在这题中数组长度为 26,如下:

    struct TrieNode {
        bool isEnd; //该结点是否是一个串的结束
        TrieNode* next[26]; //字母映射表
    };
    

    插入、匹配类似于链表操作,具体可以看这篇题解
    代码如下:

    class Trie {
    public:
        bool isEnd;
        Trie* next[26];
    
        /** Initialize your data structure here. */
        Trie() {
            isEnd = false;
            memset(next, 0, sizeof(next));
        }
        
        /** Inserts a word into the trie. */
        void insert(string word) {
            Trie* node = this;
            for(int i=0; i<word.length(); i++){
                char c = word[i];
                if(node->next[c-'a']==nullptr){ // 没有匹配上,开辟新节点
                    node->next[c-'a'] = new Trie();
                    // node = node->next[c-'a'];    // 这一句要写在外面
                }
                node = node->next[c-'a'];   // 匹配上了,匹配下一个
            }
            node->isEnd = true;
        }
        
        /** Returns if the word is in the trie. */
        bool search(string word) {
            Trie* node = this;
            for(int i=0; i<word.length(); i++){
                char c = word[i];
                if(node->next[c-'a']!=nullptr){
                    node = node->next[c-'a'];
                }else return false;
            }
            return node->isEnd;
        }
        
        /** Returns if there is any word in the trie that starts with the given prefix. */
        bool startsWith(string prefix) {
            Trie* node = this;
            for(int i=0; i<prefix.length(); i++){
                char c = prefix[i];
                if(node->next[c-'a']!=nullptr){
                    node = node->next[c-'a'];
                }else return false;
            }
            return true;
        }
    };
    
    /**
     * 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);
     */
    
  • 相关阅读:
    颜色渐变
    DELPHI 反射机制
    网络的收藏资料
    WM_Paint 消息详解
    解决EmbeddedWB弹出页面错误框的问题
    刁蛮公主第二集(纳米盘)
    第五章 用用户控件创建自定义控件
    RTX51 tiny系统要注意的问题:(关于时间片)
    第四章 高级控件编程
    CSDN新频道visual studio技术频道
  • 原文地址:https://www.cnblogs.com/flix/p/12858779.html
Copyright © 2011-2022 走看看