-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTrie.java
70 lines (63 loc) · 1.86 KB
/
Trie.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
package com.milley.structure.tree;
public class Trie {
public class TrieNode {
public char data;
public TrieNode[] children = new TrieNode[26];
public boolean isEndingChar = false;
public TrieNode(char data) {
this.data = data;
}
}
public TrieNode root;
public Trie() {
root = new TrieNode('/');
}
public void insert(String word) {
TrieNode p = root;
for (int i = 0; i < word.length(); i++) {
int index = word.charAt(i) - 'a';
if (p.children[index] == null) {
TrieNode node = new TrieNode(word.charAt(i));
p.children[index] = node;
}
p = p.children[index];
}
p.isEndingChar = true;
}
public boolean search(String word) {
TrieNode p = root;
for (int i = 0; i < word.length(); i++) {
int index = word.charAt(i) - 'a';
if (p.children[index] == null) {
return false;
} else {
p = p.children[index];
}
}
if (p.isEndingChar) {
return true;
}
return false;
}
public boolean startsWith(String prefix) {
TrieNode p = root;
for (int i = 0; i < prefix.length(); i++) {
int index = prefix.charAt(i) - 'a';
if (p.children[index] == null) {
return false;
} else {
p = p.children[index];
}
}
return true;
}
public static void main(String[] args) {
Trie obj = new Trie();
obj.insert("apple");
System.out.println(obj.search("apple"));
System.out.println(obj.search("app"));
System.out.println(obj.startsWith("app"));
obj.insert("app");
System.out.println(obj.search("app"));
}
}