算法小知识------10.19----前缀树实现

101 阅读2分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

实现Trie(前缀树)

该题出自力扣的208题——实现Trie(前缀树)【中等】,解法消化于官方题解

审题

Trie(发音类似 "try")或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完和拼写检查。

需要实现三个方法:初始化、插入、查找、前缀查找

  • 变量:

    • 当前对象数组作为树状
    • boolean值的变量决定是否当前可以结束
  • 初始化

    • 初始化当前类,并且构造长度为26的数组
    • 定义boolean初始值为false
  • 插入

    • 获取当前的对象组(从树的根节点开始)

    • 循环字符串的字符,获取当前字符的值(1-26)

    • 如果当前树的字符不存在则创建一个树对象,下标为当前字符;指针指向下一对象

      • 最后一个子树的布尔值设为true,确定为最后。
  • 查找

    • 获取当前的对象组(从树的根节点开始)
    • 循环字符,如果子树为空就直接返回false;反之循环到最后返回isEnd确定是否存在截止。
  • 前缀查找

    • 与查找同理,但是最终返回无需返回isEnd变量;直接可以返回true;

编码实现

public class TrieTree {
​
    /**
     * 原理:以对象数组去承接,以当前的ASSIC值去传
     */
​
    private TrieTree[] trie;
    private boolean isEnd;
​
    public TrieTree() {
        trie = new TrieTree[26];
        isEnd =false;
    }
​
    public void insert(String word) {
        //获取当前树
        TrieTree node = this;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            //获取当前字符的值(1-26)
            int index = c-'a';
            //如果当前树的字符不存在,则创建一个树对象
            if (node.trie[index] == null){
                node.trie[index] = new TrieTree();
            }
            //指针指向下一个对象
            node = node.trie[index];
        }
        node.isEnd = true;
    }
​
    public boolean search(String word) {
//        if (word == null){
//            return
//        }
        TrieTree node = this;
        for (int i = 0;i<word.length();i++){
            char c = word.charAt(i);
            int index = c-'a';
            if (node.trie[index] == null){
                return false;
            }
            node = node.trie[index];
        }
        return node.isEnd;
    }
​
    public boolean startsWith(String prefix) {
        TrieTree node = this;
        for (int i = 0;i<prefix.length();i++){
            char c = prefix.charAt(i);
            int index = c-'a';
            if (node.trie[index] == null){
                return false;
            }
            node = node.trie[index];
        }
        return true;
    }

1634640178(1).jpg