-
Notifications
You must be signed in to change notification settings - Fork 111
/
Copy pathsolution.java
70 lines (54 loc) · 1.94 KB
/
solution.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
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;
import java.util.*;
class Node {
int count; //Number of times this node has been visited during insertion of the strings
Node[] children; //An array of pointers that contains the pointer to the next nodes
Node() {
this.count = 0;
this.children = new Node[26];
Arrays.fill(children, null);
}
public void insert(Node current, String value) {
for(char c : value.toCharArray()) {
int index = c - 'a';
if(current.children[index] == null) {
current.children[index] = new Node();
}
current.children[index].count++;
current = current.children[index];
}
}
}
public class solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Node trie = new Node();
int n = scan.nextInt();
while(n-- > 0) {
String operation = scan.next();
String value = scan.next();
// Insertion Operation
if(operation.equals("add")) {
trie.insert(trie, value);
}
else { // Search Operation
Node currentNode = trie;
// Traverse through each level
for(char c : value.toCharArray()) {
// Maintain a reference to the Node matching the char for that level
currentNode = currentNode.children[c - 'a'];
if(currentNode == null) {
break;
}
}
// Print the number of results
System.out.println((currentNode != null) ? currentNode.count : 0);
}
}
scan.close();
}
}