-
Notifications
You must be signed in to change notification settings - Fork 0
/
ParenthesesBalance.java
50 lines (46 loc) · 1.15 KB
/
ParenthesesBalance.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
/** https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=614 #stack */
import java.util.Deque;
import java.util.LinkedList;
import java.util.Scanner;
class ParenthesesBalance {
static Character validPairChar(Character c) {
if (c == ']') {
return '[';
} else if (c == ')') {
return '(';
} else {
return c;
}
}
static String check(String str) {
Deque<Character> stack = new LinkedList<>();
for (Character c : str.toCharArray()) {
if (c == '(' || c == '[') {
stack.addFirst(c);
} else {
if (stack.isEmpty() || stack.peekFirst() != validPairChar(c)) {
return "No";
} else {
stack.pollFirst();
}
}
}
if (!stack.isEmpty()) {
return "No";
}
return "Yes";
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
// sc.nextLine();
String[] arr = new String[n];
for (int i = 0; i < n; i++) {
String str = sc.next(); // sc.nextLine();
arr[i] = str;
}
for (String str : arr) {
System.out.println(check(str));
}
}
}