2025年- H58-Lc166--208.实现Tri(前缀树)(图论,广搜)--Java版

1.题目描述

2025年- H58-Lc166--208.实现Tri(前缀树)(图论,广搜)--Java版_第1张图片

2.思路

调用辅助方法 searchPrefix(String prefix)

目的:找到这个 word 对应的最后一个字符所在的节点。

如果遍历过程中某个字符没有对应的子节点,返回 null。

检查返回的节点是否有效

如果 searchPrefix(word) 返回的节点不为 null,并且 node.isEnd == true,说明这个单词完整存在于 Trie 中。

如果是前缀但不是完整单词(即 isEnd == false),则返回 false。

3.代码实现

    //每个节点最多有26个节点(小写字母0-z)
    private Trie[] children;

    //表示该节点是否是某个单词的结尾标记
    private boolean  isEnd;
    public Trie() {
        //初始化26个字母对应的子节点
        children =new Trie[26];
        //初始时部署任何单词的结尾
        isEnd=false;

    }

    //插入有个单词到Trie中
    public void insert(String word) {
        Trie node=this;//从根节点开始
        for(int i=0;i<word.length();i++)
        {
            //从根节点开始
            char ch=word.charAt(i);
            //计算对应的数组下标(0~25)
            int index=ch-'a';
            if(node.children[index]==null)
            {
                //如果当前字符对应的子节点不存在,则创建新节点
                node.children[index]=new Trie();
            }
            //移动到子节点
            node=node.children[index];
        }
        //单词插入结束,标记成true
        node.isEnd=true;

    }

    // 判断 Trie 中是否存在完整的单词 word
    public boolean search(String word) {
        // 查找前缀对应的节点
        Trie node=searchPrefix(word);
        if(node!=null&& node.isEnd)
        {
            return true;
        }
        else {
            // 补充这一句,表示未找到完整单词
            return false;
        }


    }
    //判断Trie中是否存在以prefix为前缀的单词
    public boolean startsWith(String prefix) {
        //只要能找到该前缀节点就返回true
        return searchPrefix(prefix)!=null;

    }
    //辅助函数,查找前缀prefix对应的最后一个节点
    private Trie searchPrefix(String prefix)
    {
        Trie node=this;//从根节点开始
        for(int i=0;i<prefix.length();i++)
        {
            //当前字符
            char ch=prefix.charAt(i);
            //对应下标
            int index=ch-'a';
            if(node.children[index]==null)
            {
                //当前字符对应的子节点不存在,说明前缀不存在
                return null;
            }
            // 移动到子节点
            node=node.children[index];
        }
        // 返回最后一个节点
        return node;
    }

你可能感兴趣的:(java,leetcode,图论,java,c#)