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

示例:

输入
["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
  • wordprefix 仅由小写英文字母组成
  • insertsearchstartsWith 调用次数 总计 不超过 3 * 104

题解分析

  1. 本题是需要我们自己实现一个前缀树,其实如果理解了前缀树的原理,自己实现是比较容易的。
  2. 既然前缀树是树结构,那么首先需要定义TreeNode数据结构,而里面的成员变量应该如何设置呢?考虑到前缀树的特殊结构,它的每条边都有字母作为标志,所以需要设置一个TreeNode[] next作为邻接节点数组,而数组的下标应该是26个英文字母,它们也可以看成是邻接边。此外,还需要设置一个boolean变量用来标识一个节点是否是一个字符前缀的结束节点。
  3. 根据我们前面定义好的树节点结构,可以很容易地完成题目要求的四个方法的编写,特别是后三个方法,它们的实现逻辑都差不多,即都需要遍历字符串的每个字符,并查找前缀树中是否有相应已经插入的字符节点或边。
class Trie {

    class TreeNode{
        boolean isEnd;// 是否有字符串以该节点作为结束节点
        TreeNode[] next; // 当前节点的邻接边

        TreeNode(){
            isEnd = false;
            next = new TreeNode[26];// 字符仅由小写英文字母组成,一个节点最多26条边
        }
    }

    private TreeNode root;

    public Trie() {
        root = new TreeNode();
    }
    
    public void insert(String word) {
        TreeNode now = root;
        for(char ch : word.toCharArray()){
            if(now.next[ch - 'a'] == null){
                now.next[ch - 'a'] = new TreeNode();
            }
            now = now.next[ch - 'a'];
        }
        now.isEnd = true;
    }
    
    public boolean search(String word) {
        TreeNode now = root;
        for(char ch : word.toCharArray()){
            if(now.next[ch - 'a'] == null){
                return false;
            }
            now = now.next[ch - 'a'];
        }
        return now.isEnd;
    }
    
    public boolean startsWith(String prefix) {
        TreeNode now = root;
        for(char ch : prefix.toCharArray()){
            if(now.next[ch - 'a'] == null){
                return false;
            }
            now = now.next[ch - '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);
 */

结果展示

image

posted @ 2022-01-17 11:33  Garrett_Wale  阅读(28)  评论(0编辑  收藏  举报