Skip to content

Commit be6e145

Browse files
committed
Added a trie solution to HR
1 parent 749d0f9 commit be6e145

File tree

1 file changed

+109
-0
lines changed

1 file changed

+109
-0
lines changed
Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
import java.io.*;
2+
import java.math.*;
3+
import java.text.*;
4+
import java.util.*;
5+
import java.util.regex.*;
6+
7+
class Node {
8+
char val;
9+
Map<Character, Node> childrens;
10+
int size;
11+
12+
public Node(char val) {
13+
this.val = val;
14+
childrens = new HashMap<>();
15+
size = 0;
16+
}
17+
}
18+
19+
public class Solution {
20+
21+
/*
22+
* Complete the contacts function below.
23+
*/
24+
static int[] contacts(String[][] queries) {
25+
/*
26+
* Write your code here.
27+
*/
28+
Node root = new Node(' ');
29+
List<Integer> ans = new ArrayList<>();
30+
31+
for (String[] query : queries) {
32+
if (query[0].equals("add")) {
33+
addWord(root, query[1], 0);
34+
}
35+
else {
36+
ans.add(getWordCount(root, query[1]));
37+
}
38+
}
39+
40+
int[] res = new int[ans.size()];
41+
for (int i = 0; i < ans.size(); i++) {
42+
res[i] = ans.get(i);
43+
}
44+
45+
return res;
46+
}
47+
48+
private static int getWordCount(Node root, String s) {
49+
for (int i = 0; i < s.length(); i++) {
50+
if (root.childrens.containsKey(s.charAt(i))) {
51+
root = root.childrens.get(s.charAt(i));
52+
}
53+
else {
54+
return 0;
55+
}
56+
}
57+
58+
return root.size;
59+
}
60+
61+
private static void addWord(Node root, String s, int idx) {
62+
if (idx == s.length()) {
63+
return;
64+
}
65+
66+
if (!root.childrens.containsKey(s.charAt(idx))) {
67+
root.childrens.put(s.charAt(idx), new Node(s.charAt(idx)));
68+
}
69+
70+
root = root.childrens.get(s.charAt(idx));
71+
root.size++;
72+
73+
addWord(root, s, idx + 1);
74+
}
75+
76+
private static final Scanner scanner = new Scanner(System.in);
77+
78+
public static void main(String[] args) throws IOException {
79+
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
80+
81+
int queriesRows = Integer.parseInt(scanner.nextLine().trim());
82+
83+
String[][] queries = new String[queriesRows][2];
84+
85+
for (int queriesRowItr = 0; queriesRowItr < queriesRows; queriesRowItr++) {
86+
String[] queriesRowItems = scanner.nextLine().split(" ");
87+
88+
for (int queriesColumnItr = 0; queriesColumnItr < 2; queriesColumnItr++) {
89+
String queriesItem = queriesRowItems[queriesColumnItr];
90+
queries[queriesRowItr][queriesColumnItr] = queriesItem;
91+
}
92+
}
93+
94+
int[] result = contacts(queries);
95+
96+
for (int resultItr = 0; resultItr < result.length; resultItr++) {
97+
bufferedWriter.write(String.valueOf(result[resultItr]));
98+
99+
if (resultItr != result.length - 1) {
100+
bufferedWriter.write("\n");
101+
}
102+
}
103+
104+
bufferedWriter.newLine();
105+
106+
bufferedWriter.close();
107+
}
108+
}
109+

0 commit comments

Comments
 (0)