-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathTrie.java
More file actions
76 lines (68 loc) · 2.3 KB
/
Trie.java
File metadata and controls
76 lines (68 loc) · 2.3 KB
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
class TrieNode {
TrieNode[] children = new TrieNode[26];
boolean isEndOfWord = false;
}
public class Trie {
private TrieNode root = new TrieNode();
public void insert(String word) {
TrieNode node = root;
for (char ch : word.toCharArray()) {
int index = ch - 'a';
if (node.children[index] == null) node.children[index] = new TrieNode();
node = node.children[index];
}
node.isEndOfWord = true;
}
public boolean search(String word) {
TrieNode node = root;
for (char ch : word.toCharArray()) {
int index = ch - 'a';
if (node.children[index] == null) return false;
node = node.children[index];
}
return node.isEndOfWord;
}
public boolean startsWith(String prefix) {
TrieNode node = root;
for (char ch : prefix.toCharArray()) {
int index = ch - 'a';
if (node.children[index] == null) return false;
node = node.children[index];
}
return true;
}
private boolean delete(TrieNode node, String word, int depth) {
if (node == null) return false;
if (depth == word.length()) {
if (!node.isEndOfWord) return false;
node.isEndOfWord = false;
for (TrieNode child : node.children) if (child != null) return false;
return true;
}
int index = word.charAt(depth) - 'a';
if (delete(node.children[index], word, depth + 1)) {
node.children[index] = null;
if (!node.isEndOfWord) {
for (TrieNode child : node.children) if (child != null) return false;
return true;
}
}
return false;
}
public void remove(String word) {
delete(root, word, 0);
}
public static void main(String[] args) {
Trie trie = new Trie();
trie.insert("apple");
trie.insert("app");
trie.insert("bat");
System.out.println(trie.search("apple"));
System.out.println(trie.search("app"));
System.out.println(trie.search("appl"));
System.out.println(trie.startsWith("ap"));
trie.remove("app");
System.out.println(trie.search("app"));
System.out.println(trie.search("apple"));
}
}