-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path00208-implement_trie_prefix_tree.java
76 lines (60 loc) · 1.95 KB
/
00208-implement_trie_prefix_tree.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// 208: Implement Trie Prefix Tree
// https://leetcode.com/problems/implement-trie-prefix-tree
class Trie {
class TrieNode {
public TrieNode[] children = new TrieNode[26];
public boolean isWord;
public TrieNode() {
for (int i=0; i<26; i++) children[i] = null;
isWord = false;
}
}
public TrieNode root;
public Trie() {
root = new TrieNode();
}
public void insert(String word) {
TrieNode node = root;
int current = 0;
for (int i=0; i<word.length(); i++) {
current = word.charAt(i) - 'a';
if (node.children[current] == null)
node.children[current] = new TrieNode();
node = node.children[current];
}
node.isWord = true;
}
public boolean search(String word) {
TrieNode node = root;
int current = 0;
for (int i=0; i<word.length(); i++) {
current = word.charAt(i) - 'a';
if (node.children[current] == null)
return false;
node = node.children[current];
}
return node.isWord;
}
public boolean startsWith(String prefix) {
TrieNode node = root;
int current = 0;
for (int i=0; i<prefix.length(); i++) {
current = prefix.charAt(i) - 'a';
if (node.children[current] == null) {
return false;
}
node = node.children[current];
}
return true;
}
public static void main(String[] args) {
Trie trie = new Trie();
// OPERATION
trie.insert("apple");
System.out.println(trie.search("apple") ? "true" : "false");
System.out.println(trie.search("app") ? "true" : "false");
System.out.println(trie.startsWith("app") ? "true" : "false");
trie.insert("app");
System.out.println(trie.search("app") ? "true" : "false");
}
}