forked from alexprut/HackerRank
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.java
51 lines (46 loc) · 1.35 KB
/
Solution.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
import java.util.*;
class Solution{
private static boolean isBalanced(String query) {
Stack<Character> s = new Stack<Character>();
for (int i = 0; i < query.length(); i++) {
if (query.charAt(i) == '(' || query.charAt(i) == '[' || query.charAt(i) == '{') {
s.push(query.charAt(i));
}
if (query.charAt(i) == ')' || query.charAt(i) == ']' || query.charAt(i) == '}') {
if (s.empty()) {
return false;
}
if (query.charAt(i) == ')') {
if (s.peek() == '(') {
s.pop();
} else {
return false;
}
}
if (query.charAt(i) == ']') {
if (s.peek() == '[') {
s.pop();
} else {
return false;
}
}
if (query.charAt(i) == '}') {
if (s.peek() == '{') {
s.pop();
} else {
return false;
}
}
}
}
return s.empty();
}
public static void main(String []argh)
{
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String input=sc.next();
System.out.println(Solution.isBalanced(input));
}
}
}