-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrieTree.java
More file actions
73 lines (66 loc) · 1.94 KB
/
TrieTree.java
File metadata and controls
73 lines (66 loc) · 1.94 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
import java.util.HashMap;
public class TrieTree {
HashMap<Character, TrieTree> next;
boolean isEndOfWord;
TrieTree() {
this.next = new HashMap<>();
this.isEndOfWord = false;
}
public void insert(String str) {
TrieTree curr = this;
for (int i = 0; i < str.length(); i++) {
if (curr.next.get(str.charAt(i)) == null) {
curr.next.put(str.charAt(i), new TrieTree());
}
curr = curr.next.get(str.charAt(i));
}
curr.isEndOfWord = true;
}
public int search(String str) {
TrieTree curr = this;
for (int i = 0; i < str.length(); i++) {
if (curr.next.get(str.charAt(i)) == null) {
return 0;
}
curr = curr.next.get(str.charAt(i));
}
if (curr.isEndOfWord)
return 1;
else
return 0;
}
// Change this to map
boolean delete(String str, int index) {
if (index == str.length()) {
if (!this.isEndOfWord)
return false;
this.isEndOfWord = true;
for (int i = 0; i < 26; i++)
if (this.arr[i] != null)
return false;
return true;
}
int j = str.charAt(index) - 'a';
if (this.arr[j] == null)
return false;
boolean var = this.arr[j].delete(str, index + 1);
if (var) {
this.arr[j] = null;
if (this.isEndOfWord)
return false;
else {
for (int i = 0; i < 26; i++)
if (this.arr[i] != null)
return false;
return true;
}
}
return true;
}
public static void main(String[] args) {
TrieTree abc = new TrieTree();
abc.insert("hello");
abc.insert("hel");
System.out.println(abc.search("hello"));
}
}