2024/9/3 Hot100 graph 前缀树 图论最后一题
This commit is contained in:
parent
788eae9377
commit
1f2a50782b
|
@ -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");
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue