2021/4/14 实现 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 。

示例

输入
["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. 要存储一个字典,需要用到树状结构。如下图,存储单词“shell”,“should”,“sand”,“set”;
    图片说明
  2. 显然这是一个多叉树,也就是每个节点都维护一个节点数组,英文字母有 26 个,所以维护容量为 26 的节点数组。为何不是字符数组呢:
    • 只有是节点数组,才可以实现遍历的功能,而字符数组不能;
    • 节点数组容量为26,可以计算 ASCII 来代替字符;
      图片说明
  3. 为了检测树里是否有这个单词,我们需要维护一个布尔值 isEnd,每次存储单词之后都在最后一个字符的节点的 isEnd 设置为 true,在遍历时,只有遍历到最后一个字母不为 null 且 isEnd 为 true,才说明树里存储了这个单词。

Java 代码实现

class Trie {
    private Trie[] vals;
    private boolean isEnd;
    /** Initialize your data structure here. */
    public Trie() {
        vals = new Trie[26];
        isEnd = false;
    }

    /** Inserts a word into the trie. */
    public void insert(String word) {
        Trie node = this;
        for (char c : word.toCharArray()) {
            if (node.vals[c - 'a'] == null) {
                node.vals[c - 'a'] = new Trie();
            }
            node = node.vals[c - 'a'];
        }
        node.isEnd = true;
    }

    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        Trie node = this;
        for (char c : word.toCharArray()) {
            if (node.vals[c - 'a'] == null) return false;
            node = node.vals[c - 'a'];
        }
        return node.isEnd;
    }

    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        Trie node = this;
        for (char c : prefix.toCharArray()) {
            if (node.vals[c - 'a'] == null) return false;
            node = node.vals[c - 'a'];
        }
        return true;
    }
}

/**
 * Your Trie object will be instantiated and called as such:
 * Trie obj = new Trie();
 * obj.insert(word);
 * boolean param_2 = obj.search(word);
 * boolean param_3 = obj.startsWith(prefix);
 */
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务