2024/9/3 Hot100 graph 前缀树 图论最后一题

This commit is contained in:
linlihong 2024-09-05 11:12:18 +08:00
parent 788eae9377
commit 1f2a50782b
1 changed files with 63 additions and 0 deletions

View File

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