File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change 1+ class Trie {
2+ Node root;
3+
4+ public Trie() {
5+ root = new Node('\0'); //dummy node
6+ }
7+
8+ public void insert(String word) {
9+ Node curr = root;
10+ for (char x : word.toCharArray()) {
11+ if (curr.children[x - 'a'] == null) {
12+ curr.children[x - 'a'] = new Node(x);
13+ }
14+ curr = curr.children[x - 'a'];
15+ }
16+ curr.isWord = true;
17+ }
18+
19+ public boolean search(String word) {
20+ Node res = getLast(word);
21+ return (res != null && res.isWord);
22+ }
23+
24+ //helper method
25+ public Node getLast(String word) {
26+ Node curr = root;
27+ for (char x : word.toCharArray()) {
28+ if (curr.children[x - 'a'] == null) {
29+ return null;
30+ }
31+
32+ curr = curr.children[x - 'a'];
33+ }
34+ return curr;
35+ }
36+
37+ public boolean startsWith(String prefix) {
38+ Node res = getLast(prefix);
39+ if (res == null) return false;
40+ return true;
41+ }
42+
43+ class Node {
44+ private char value;
45+ private boolean isWord;
46+ private Node[] children;
47+
48+ public Node(char val) {
49+ this.value = val;
50+ this.isWord = false;
51+ this.children = new Node[26];
52+ }
53+ }
54+ }
You can’t perform that action at this time.
0 commit comments