-
Notifications
You must be signed in to change notification settings - Fork 11
/
BalancedBrackets.java
60 lines (50 loc) Β· 1.77 KB
/
BalancedBrackets.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
// https://www.hackerrank.com/challenges/balanced-brackets/problem
package stacks;
import java.util.Scanner;
import java.util.Stack;
public class BalancedBrackets {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int queries = scanner.nextInt();
while (queries-- > 0) {
String string = scanner.next();
System.out.println(isBalanced(string));
}
}
private static String isBalanced(String string) {
return isBalancedBrackets(string) ? "YES" : "NO" ;
}
private static boolean isBalancedBrackets(String string) {
Stack<Character> brackets = new Stack<>();
for (int index = 0 ; index < string.length() ; index++) {
char character = string.charAt(index);
if (isOpeningBrace(character)) {
brackets.push(character);
} else if (isClosingBrace(character)) {
if (!brackets.isEmpty() && brackets.peek() == inverse(character)) {
brackets.pop();
} else {
return false;
}
}
}
return brackets.isEmpty();
}
private static boolean isOpeningBrace(char character) {
return character == '(' || character == '{' || character == '[';
}
private static boolean isClosingBrace(char character) {
return character == ')' || character == '}' || character == ']';
}
private static char inverse(char character) {
switch (character) {
case '(' : return ')';
case '{' : return '}';
case '[' : return ']';
case ')' : return '(';
case '}' : return '{';
case ']' : return '[';
}
return '-';
}
}