-
Notifications
You must be signed in to change notification settings - Fork 2
/
Main.java
112 lines (91 loc) Β· 2.88 KB
/
Main.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package _2020_KAKAO_BLIND_RECRUITMENT.P4;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Solution sol = new Solution();
String[] words = {"frodo", "front", "frost", "frozen", "frame", "kakao"};
String[] queries = {"fro??", "????o", "fr???", "fro???", "pro?"};
System.out.println(Arrays.toString(sol.solution(words, queries)));
}
}
class Solution {
static Trie[] dict = new Trie[10001];
public int[] solution(String[] words, String[] queries) {
int[] answer = new int[queries.length];
for (String word : words) {
int len = word.length();
if (dict[len] == null) dict[len] = new Trie();
dict[len].insertFront(word);
dict[len].insertBack(word);
}
for (int i = 0; i < queries.length; i++) {
int len = queries[i].length();
if (dict[len] == null) answer[i] = 0;
else if (queries[i].charAt(0) != '?') answer[i] = dict[len].findFront(queries[i]);
else answer[i] = dict[len].findBack(queries[i]);
}
return answer;
}
}
class Trie {
Node rootFront = new Node();
Node rootBack = new Node();
void insertFront(String word) {
Node current = rootFront;
for (int i = 0; i < word.length(); i++) {
current.count ++;
char c = word.charAt(i);
if (!current.hasChild(c)) {
current.children[c - 'a'] = new Node();
}
current = current.getChild(c);
}
}
void insertBack(String word) {
Node current = rootBack;
for (int i = word.length() - 1; i >= 0; i--) {
current.count ++;
char c = word.charAt(i);
if (!current.hasChild(c)) {
current.children[c - 'a'] = new Node();
}
current = current.getChild(c);
}
}
int findFront(String query) {
Node current = rootFront;
for (int i = 0; i < query.length(); i++) {
char q = query.charAt(i);
if (q == '?') break;
if (current.hasChild(q)) {
current = current.getChild(q);
} else {
return 0;
}
}
return current.count;
}
int findBack(String query) {
Node current = rootBack;
for (int i = query.length() - 1; i >= 0; i--) {
char q = query.charAt(i);
if (q == '?') break;
if (current.hasChild(q)) {
current = current.getChild(q);
} else {
return 0;
}
}
return current.count;
}
}
class Node {
Node[] children = new Node[26];
int count = 0;
boolean hasChild(char c) {
return children[c - 'a'] != null;
}
Node getChild(char c) {
return children[c - 'a'];
}
}