-
Notifications
You must be signed in to change notification settings - Fork 0
/
PackedPrefix.java
79 lines (79 loc) · 2.76 KB
/
PackedPrefix.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
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class PackedPrefix {
public static void main(String[] args){
try(BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out))){
int n = Integer.parseInt(reader.readLine());
String[] data = new String[n];
for (int i = 0; i < n; i++) {
String raw = reader.readLine();
data[i] = openString(raw);
}
int min = data[0].length();
for (int i = 0; i < n; i++) {
int x = data[i].length();
if(x < min) {
min = x;
}
}
prefix(data, min, writer);
} catch(Exception ex){
System.out.println(ex.getMessage());
}
}
public static String openString(String s){
Stack<Integer> numbers = new Stack<>();
Stack<List<Character>> letters = new Stack<>();
StringBuilder result = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char letter = s.charAt(i);
if(Character.isAlphabetic(letter)){
if(letters.empty()){
result.append(letter);
} else {
letters.peek().add(letter);
}
} else if(Character.isDigit(letter)){
List<Character> list = new ArrayList<>();
numbers.add(letter - 48);
letters.add(list);
} else if(letter == ']'){
int n = numbers.pop();
List<Character> list = letters.pop();
if(letters.empty()){
for (int j = 0; j < n; j++) {
for (char x: list) {
result.append(x);
}
}
} else {
List<Character> list1 = letters.peek();
for (int j = 0; j < n; j++) {
list1.addAll(list);
}
}
}
}
return result.toString();
}
public static void prefix(String[] data, int min, BufferedWriter writer) throws IOException {
for (int i = 0; i < min; i++) {
char letter = data[0].charAt(i);
boolean check = true;
for (String word: data) {
if(letter != word.charAt(i)){
check = false;
break;
}
}
if(check){
writer.write(Character.toString(letter));
} else{
break;
}
}
}
}