-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsolution.java
More file actions
84 lines (71 loc) · 2.31 KB
/
solution.java
File metadata and controls
84 lines (71 loc) · 2.31 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
80
81
82
83
84
import java.io.*;
public class Solution {
public static void main(String... args) {
// Scanner in = new Scanner(System.in);
// in.nextInt();
final String filename = "input-01.txt";
File f = new File(filename);
try {
FileReader fr = new FileReader(f.getAbsoluteFile());
BufferedReader br = new BufferedReader(fr);
int count = Integer.parseInt(br.readLine());
Trie trie = new Trie();
for (int x=0; x < count; x++) {
String[] parts = br.readLine().split(" ");
if ("add".equals(parts[0])) {
trie.add(parts[1]);
} else {
System.out.println(trie.count(parts[1]));
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static class Trie {
TrieNode root;
public Trie() {
this.root = new TrieNode();
}
public void add(String word) {
TrieNode current = this.root;
for (char ch: word.toCharArray()) {
if (current.children[getCharIndex(ch)] == null) {
current.children[getCharIndex(ch)] = new TrieNode(ch);
} else {
current.children[getCharIndex(ch)].count++;
}
current = current.children[getCharIndex(ch)];
}
}
public int count(String keyword) {
TrieNode current = this.root;
for (char ch: keyword.toCharArray()) {
if (current.children[getCharIndex(ch)] == null) {
return 0;
}
current = current.children[getCharIndex(ch)];
}
return current.count;
}
public int getCharIndex(Character ch) {
return ch - 'a';
}
}
public static class TrieNode {
final int size = 26;
TrieNode[] children;
Character data;
int count;
public TrieNode() {
this(null);
}
public TrieNode(Character data) {
this.data = data;
children = new TrieNode[size];
count = 1;
}
}
}