-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBrackets extreme edition.java
56 lines (41 loc) · 1.26 KB
/
Brackets extreme edition.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
import java.util.*;
import java.io.*;
import java.math.*;
class Solution {
private static final String OPEN = "([{";
private static final String CLOSE = ")]}";
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
String expression = in.next();
// Write an action using System.out.println()
// To debug: System.err.println("Debug messages...");
//System.out.println("true/false");
System.out.println(isBalanced(expression));
}
public static boolean isBalanced(String expression) {
Stack<Character> s = new Stack<Character>();
boolean balanced = true;
for (int index = 0; balanced && index < expression.length(); index++) {
char nextCh = expression.charAt(index);
if (isOpen(nextCh)) {
s.push(nextCh);
}
else if (isClose(nextCh)) {
if (s.empty()) {
balanced = false;
break;
}
else {
balanced = (OPEN.indexOf(s.pop()) == CLOSE.indexOf(nextCh));
}
}
}
return (balanced && s.empty());
}
private static boolean isOpen(char ch) {
return OPEN.indexOf(ch) > -1;
}
private static boolean isClose(char ch) {
return CLOSE.indexOf(ch) > -1;
}
}