-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathImplementTrie
More file actions
79 lines (63 loc) · 2.26 KB
/
ImplementTrie
File metadata and controls
79 lines (63 loc) · 2.26 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
77
78
79
class TrieNode {
char character;
TrieNode[] alphabet;
boolean endsWord;
public TrieNode(char character) {
this.character = character;
alphabet = new TrieNode[26];
endsWord = false;
}
}
public class ImplementTrie {
TrieNode root = new TrieNode('#');
public void insert(String word) {
TrieNode currentNode = root;
for (int i = 0; i < word.length(); i++) {
char nextCharacter = word.charAt(i);
int index = nextCharacter - 'a';
if (currentNode.alphabet[index] == null) {
currentNode.alphabet[index] = new TrieNode(nextCharacter);
}
currentNode = currentNode.alphabet[index];
}
currentNode.endsWord = true;
}
public boolean search(String word) {
TrieNode currentNode = root;
for (int i = 0; i < word.length(); i++) {
char nextCharacter = word.charAt(i);
int index = nextCharacter - 'a';
if (currentNode.alphabet[index] == null) {
return false;
}
currentNode = currentNode.alphabet[index];
}
return currentNode.endsWord;
}
public boolean startsWith(String word) {
TrieNode currentNode = root;
for (int i = 0; i < word.length(); i++) {
char nextCharacter = word.charAt(i);
int index = nextCharacter - 'a';
if (currentNode.alphabet[index] == null) {
return false;
}
currentNode = currentNode.alphabet[index];
}
return true;
}
public static void main(String[] args) {
ImplementTrie trie = new ImplementTrie();
trie.insert("apple");
trie.insert("banana");
trie.insert("carrot");
System.out.println(trie.search("apple")); // true
System.out.println(trie.search("banana")); // true
System.out.println(trie.search("carrot")); // true
System.out.println(trie.search("orange")); // false
System.out.println(trie.startsWith("app")); // true
System.out.println(trie.startsWith("ban")); // true
System.out.println(trie.startsWith("car")); // true
System.out.println(trie.startsWith("ora")); // false
}
}