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;
    }
}
相关推荐
IronMurphy6 分钟前
【算法五十七】146. LRU 缓存
算法·缓存
ywl4708120879 分钟前
jwt生产token,简单版helloworld
java·数据库·spring
未若君雅裁14 分钟前
生产问题排查与性能瓶颈定位:日志、监控、链路追踪、压测与Arthas
java·web安全
器灵科技21 分钟前
AI视频工具实测:Seedance/可灵/HappyHorse谁最能打?
java·运维·数据库·人工智能·github
南部余额33 分钟前
RabbitMQ 进阶:延迟队列完全指南
java·分布式·spring·rabbitmq
phltxy35 分钟前
Spring AI Agents 智能体模式实战
java·人工智能·spring
凌波粒39 分钟前
LeetCode--108.将有序数组转换为二叉搜索树(二叉树)
算法·leetcode·职场和发展
liulilittle39 分钟前
KCC:在 BBR 思路上的一次探索
网络·tcp/ip·算法·bbr·通信·拥塞控制·kcc
码云骑士43 分钟前
13-列表append的底层真相(上)-listobject源码中的预分配策略
开发语言·python
摇滚侠1 小时前
MyBatis 入门到项目实战 特殊 SQL 的执行 34-37
java·sql·mybatis