-
Notifications
You must be signed in to change notification settings - Fork 6
/
Solution.java
75 lines (64 loc) · 1.93 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
71
72
73
74
75
/*
* DeveloperName(): Jignesh Chudasama
* GithubName(): https://github.com/Jignesh-81726
*/
import java.util.Scanner;
import java.util.HashMap;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
Trie trie = new Trie();
for (int i = 0; i < n; i++) {
String operation = scan.next();
String contact = scan.next();
if (operation.equals("add")) {
trie.add(contact);
} else if (operation.equals("find")) {
System.out.println(trie.find(contact));
}
}
scan.close();
}
}
/* Based loosely on tutorial video in this problem */
class TrieNode {
private HashMap<Character, TrieNode> children = new HashMap<>();
public int size = 0; // this was the main trick to decrease runtime to pass tests.
public void putChildIfAbsent(char ch) {
children.putIfAbsent(ch, new TrieNode());
}
public TrieNode getChild(char ch) {
return children.get(ch);
}
}
class Trie {
TrieNode root = new TrieNode();
Trie(){} // default constructor
Trie(String[] words) {
for (String word : words) {
add(word);
}
}
public void add(String str) {
TrieNode curr = root;
for (int i = 0; i < str.length(); i++) {
Character ch = str.charAt(i);
curr.putChildIfAbsent(ch);
curr = curr.getChild(ch);
curr.size++;
}
}
public int find(String prefix) {
TrieNode curr = root;
/* Traverse down tree to end of our prefix */
for (int i = 0; i < prefix.length(); i++) {
Character ch = prefix.charAt(i);
curr = curr.getChild(ch);
if (curr == null) {
return 0;
}
}
return curr.size;
}
}