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;
    }
}
相关推荐
ejinxian12 分钟前
PHP 超文本预处理器 发布 8.5 版本
开发语言·php
Codebee15 分钟前
“自举开发“范式:OneCode如何用低代码重构自身工具链
java·人工智能·架构
weixin_4461224631 分钟前
LinkedList剖析
算法
程序无bug31 分钟前
手写Spring框架
java·后端
程序无bug33 分钟前
Spring 面向切面编程AOP 详细讲解
java·前端
就是有点傻38 分钟前
在C#中,可以不实例化一个类而直接调用其静态字段
c#
软件黑马王子38 分钟前
C#系统学习第八章——字符串
开发语言·学习·c#
阿蒙Amon39 分钟前
C#读写文件:多种方式详解
开发语言·数据库·c#
全干engineer44 分钟前
Spring Boot 实现主表+明细表 Excel 导出(EasyPOI 实战)
java·spring boot·后端·excel·easypoi·excel导出
Da_秀1 小时前
软件工程中耦合度
开发语言·后端·架构·软件工程