-
Notifications
You must be signed in to change notification settings - Fork 0
/
Task3.java
112 lines (93 loc) · 2.79 KB
/
Task3.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
/* Kornilov Nikita, M3102, 29.10.2020 */
package Sem1.Lab4;
import java.io.*;
import java.util.*;
public class Task3 {
BufferedReader br;
StringTokenizer in;
PrintWriter out;
public static void main(String[] args) {
String inputFile = "brackets.in";
String outputFile = "brackets.out";
new Task3().run(inputFile, outputFile);
}
public String nextToken() throws IOException {
while (in == null || !in.hasMoreTokens()) {
in = new StringTokenizer(br.readLine());
}
return in.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public void solve() throws IOException {
String tmp;
Stack stack;
boolean flag, working = true;
while (working) {
try {
flag = true;
stack = new Stack(10000);
tmp = nextToken();
for (char c : tmp.toCharArray()) {
switch (c) {
case '(':
case '[': {
stack.push(c);
break;
}
case ')': {
char ex = stack.pop();
if (ex != '(') {
flag = false;
}
break;
}
case ']': {
char ex = stack.pop();
if (ex != '[') {
flag = false;
}
break;
}
}
}
if (flag)
flag = stack.size == 0;
if (flag)
out.write("YES\n");
else out.write("NO\n");
} catch (NullPointerException ignored) {
working = false;
}
}
}
public void run(String inputFile, String outputFile) {
try {
br = new BufferedReader(new FileReader(inputFile));
out = new PrintWriter(outputFile);
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
private static class Stack {
char[] array;
int size;
public Stack(int length) {
array = new char[length];
size = 0;
}
public void push(char element) {
array[size++] = element;
}
public char pop() {
if (size != 0)
return array[--size];
else
return '0';
}
}
}