54、图论-实现Trie前缀树

思路:

主要是构建一个trie前缀树结构。如果构建呢?看题意,应该当前节点对象下有几个属性:

1、next节点数组

2、是否为结尾

3、当前值

代码如下:

java 复制代码
class Trie {

    class Node {
        boolean end;
        Node[] nexts;

        public Node() {
            end = false;
            nexts = new Node[26];
        }
    }

    public Node root;

    public Trie() {
        root = new Node();
    }

    public void insert(String word) {
        if (word == null) {
            return;
        }
        char[] chs = word.toCharArray();
        Node node = root;
        int path;
        for (int i = 0; i < chs.length; i++) {
            path = chs[i] - 'a';
            if (node.nexts[path] == null) {
                node.nexts[path] = new Node();
            }
            node = node.nexts[path];
        }
        node.end = true;
    }

    public boolean search(String word) {
        if (word == null) {
            return false;
        }
        char[] chs = word.toCharArray();
        Node node = root;
        int path;
        for (int i = 0; i < chs.length; i++) {
            path = chs[i] - 'a';
            if (node.nexts[path] == null) {
                return false;
            }
            node = node.nexts[path];
        }
        return node.end;
    }

    public boolean startsWith(String prefix) {
        if (prefix == null) {
            return false;
        }
        char[] chs = prefix.toCharArray();
        int path;
        Node node = root;
        for (int i = 0; i < chs.length; i++) {
            path = chs[i] - 'a';
            if (node.nexts[path] == null) {
                return false;
            }
            node = node.nexts[path];
        }
        return true;
    }
}
相关推荐
市场部需要一个软件开发岗位6 分钟前
JAVA开发常见安全问题:纵向越权
java·数据库·安全
大闲在人10 分钟前
8. 供应链与制造过程术语:产能
算法·制造·供应链管理·智能制造·工业工程
一只小小的芙厨15 分钟前
寒假集训笔记·以点为对象的树形DP
c++·算法
历程里程碑19 分钟前
普通数组----合并区间
java·数据结构·python·算法·leetcode·职场和发展·tornado
执风挽^36 分钟前
Python基础编程题2
开发语言·python·算法·visual studio code
程序员泠零澪回家种桔子38 分钟前
Spring AI框架全方位详解
java·人工智能·后端·spring·ai·架构
Z9fish1 小时前
sse哈工大C语言编程练习20
c语言·开发语言·算法
CodeCaptain1 小时前
nacos-2.3.2-OEM与nacos3.1.x的差异分析
java·经验分享·nacos·springcloud
晓13131 小时前
第六章 【C语言篇:结构体&位运算】 结构体、位运算全面解析
c语言·算法
iAkuya1 小时前
(leetcode)力扣100 61分割回文串(回溯,动归)
算法·leetcode·职场和发展