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"); + } +}