【leetcode】208 实现 Trie (前缀树)(字符串,查找)

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

题目描述

实现一个 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

说明:

  • 你可以假设所有的输入都是由小写字母 a-z 构成的。
  • 保证所有输入均为非空字符串。

思路

之前没有接触过前缀树的概念,单纯从题目要实现的功能出发,用unordered_set模拟实现,实现过程很简单,但是耗时911ms不忍直视,速度垫底。

下面详细地介绍一下前缀树:

1 概念

Trie树,又名前缀树、字典树,是一种多叉树,是哈希树的一个变种。
在这里插入图片描述

2 基本性质

  • 根节点不包含字符,除根节点外的每个子节点都包含一个字符
  • 从根节点到某一节点,路径上经过的字符连接起来,就是该节点对应的字符串
  • 每个节点的所有子节点包含的字符都不相同

3 使用场景

典型应用是用于统计,排序和保存大量的字符串(不仅限于字符串),经常被搜索引擎系统用于文本词频统计。

4 优点

利用字符串的公共前缀减少查询时间,最大限度的减少无谓的字符串比较,查询效率比哈希树高。

下面介绍该题实现前缀树的方法:
(1)每个节点建立一个长度为26的数组(映射子节点a~z字符是否存在)用来存放下一个节点的地址
(2)节点上增加一个标志isEnd用来表明 该节点是否是路径(单词)的结尾,用于search时判断
(3)遍历的时候就查找对应的子数组next[ch]是否为空来匹配前缀字符

该方法通过的时间为112ms,超过94%的方案。果然利用字符串的公共前缀减少了大量的查询时间。并且每个节点直接建立长度为26的数组相当于建立一个哈希表来查找,加快了查询时间。

代码

class Trie {
private:
    Trie* next[26] = {};
    bool isEnd= false;      // 表明是否是单词结尾
public:
    /** Initialize your data structure here. */
    Trie() {}

    /** Inserts a word into the trie. */
    void insert(string word) {
        Trie* node = this;
        for(char ch:word){
            ch -= 'a';      // 得到字符的序号
            if(!node->next[ch]){
                // 若当前字符不存在 创建新节点
                node->next[ch] = new Trie();
            }
            node = node->next[ch];
        }
        node->isEnd = true;
    }

    /** Returns if the word is in the trie. */
    bool search(string word) {
        Trie* node = this;
        for(char ch: word){
            ch-= 'a';
            if(!node->next[ch]) // 如果不匹配
                return false;
            node = node->next[ch];
        }
        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 (char ch:prefix){
            ch -= 'a';
            if(!node->next[ch])
                return false;
            node = node->next[ch];
        }
        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);
 */

猜你喜欢

转载自blog.csdn.net/zjwreal/article/details/89416457
今日推荐