-
Notifications
You must be signed in to change notification settings - Fork 2
/
TrieTest.java
54 lines (46 loc) Β· 1.28 KB
/
TrieTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package Trie;
public class TrieTest {
public static void main(String[] args) {
Trie t = new Trie();
t.insert("ABC");
System.out.println(t.checkWord("ABC"));
System.out.println(t.checkWord("ABD"));
System.out.println(t.checkWord("AB"));
}
}
class Trie {
TrieNode root = new TrieNode();
void insert(String word) {
TrieNode current = root;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if (!current.hasChild(c)) {
current.children[c - 'A'] = new TrieNode();
}
current = current.getChild(c);
}
current.isEnd = true;
}
boolean checkWord(String word) {
TrieNode current = root;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if (current.hasChild(c)) {
current = current.getChild(c);
} else {
return false;
}
}
return current.isEnd;
}
}
class TrieNode {
TrieNode[] children = new TrieNode[26]; // μνλ²³ λλ¬Έμλ§
boolean isEnd;
TrieNode getChild(char c) {
return children[c - 'A'];
}
boolean hasChild(char c) {
return children[c - 'A'] != null;
}
}