From 1f2a50782bffc9639a4a77e70355c7d961783cf9 Mon Sep 17 00:00:00 2001 From: linlihong <747682928@qq.com> Date: Thu, 5 Sep 2024 11:12:18 +0800 Subject: [PATCH] =?UTF-8?q?2024/9/3=20Hot100=20graph=20=E5=89=8D=E7=BC=80?= =?UTF-8?q?=E6=A0=91=20=E5=9B=BE=E8=AE=BA=E6=9C=80=E5=90=8E=E4=B8=80?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/cool/hot100/graph/Trie.java | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 src/main/java/com/cool/hot100/graph/Trie.java diff --git a/src/main/java/com/cool/hot100/graph/Trie.java b/src/main/java/com/cool/hot100/graph/Trie.java new file mode 100644 index 0000000..ded9d9e --- /dev/null +++ b/src/main/java/com/cool/hot100/graph/Trie.java @@ -0,0 +1,63 @@ +package com.cool.hot100.graph; + +import org.junit.Test; + +/** + * Created with IntelliJ IDEA. + * + * @Author: Cool + * @Date: 2024/09/05/09:53 + * DayNumber 1 + * Hard 2 + * Level ? + */ +public class Trie { + + Trie[] children = new Trie[26]; + boolean isEnd = false; + + + public Trie() { + + } + + public void insert(String word) { + Trie node = this; + char[] wordCharArray = word.toCharArray(); + for (char c : wordCharArray) { + if (node.children[c - 'a'] == null) { + node.children[c - 'a'] = new Trie(); + } + node = node.children[c - 'a']; + } + node.isEnd = true; + } + + public boolean search(String word) { + Trie node = searchNode(word); + return node != null && node.isEnd; + } + + public boolean startsWith(String prefix) { + Trie node = searchNode(prefix); + return node != null; + } + + private Trie searchNode(String word) { + char[] wordCharArray = word.toCharArray(); + Trie node = this; + for (char c : wordCharArray) { + if (node.children[c - 'a'] == null) { + return null; + } + node = node.children[c - 'a']; + } + return node; + } + @Test + public void test(){ + Trie trie = new Trie(); + trie.insert("hotdog"); + trie.startsWith("dog"); + } +}