-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMain.java
93 lines (82 loc) Β· 2.59 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
package Stack.P2504;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Stack;
public class Main {
static String input;
static Stack<Element> stack;
static boolean isValid = true;
public static void main(String[] args) throws Exception{
// System.setIn(new FileInputStream("src/Stack/P2504/input.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
input = br.readLine();
stack = new Stack<>();
for (int i = 0; i < input.length(); i++) {
char target = input.charAt(i);
if (target == '(' || target == '[') {
stack.push(new Element(target));
} else if (target == ')') {
int value = 0;
while (!stack.empty() && stack.peek().isValue) {
value += stack.pop().value;
}
if (value == 0) value = 1;
if (!stack.empty() && stack.peek().command == '('){
stack.pop();
stack.push(new Element(2 * value));
} else {
isValid = false;
break;
}
} else if (target == ']') {
int value = 0;
while (!stack.empty() && stack.peek().isValue) {
value += stack.pop().value;
}
if (value == 0) value = 1;
if (!stack.empty() && stack.peek().command == '['){
stack.pop();
stack.push(new Element(3 * value));
} else {
isValid = false;
break;
}
} else {
isValid = false;
break;
}
// System.out.println(stack.toString());
}
int result = 0;
if (isValid) {
while (!stack.empty()) {
Element target = stack.pop();
if (!target.isValue) {
result = 0;
break;
}
result += target.value;
}
}
System.out.println(result);
}
}
class Element {
boolean isValue;
int value;
char command;
public Element(int value) {
this.isValue = true;
this.value = value;
}
public Element(char command) {
this.isValue = false;
this.command = command;
}
@Override
public String toString() {
if (isValue) return "" + value;
else return "" + command;
}
}