This is the Java solution to the Balanced Brackets problem I postead earlier, as I said, we are going to be using stacks to tackle this problem, taking advantage of Java’s built-in Stack class.

I already explained the gist of the solution in the problem post, so I will just briefly mention it here.

We will be iterating through the input string to read each character it has, and we will be doing one of two things with each character:

  • If the character is an opening bracket (i.e. (, {, [), we will push it in to the stack.
  • If the character is a closing bracket (i.e. )}]and last element in the stack is its equivalent opening bracket, we will pop the last element of the stack, otherwise we have an unbalanced bracket string.

If we end up with an empty stack, then we have a balanced bracket string.

Here is the code:


import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

public static boolean isBalanced(String expression) {

Stack<Character> bracketStack = new Stack<>();
for(char bracket : expression.toCharArray()){
switch(bracket){
case ')':
if (bracketStack.isEmpty() || bracketStack.peek() != '(') return false;
else bracketStack.pop();
break;
case '}':
if (bracketStack.isEmpty() || bracketStack.peek() != '{') return false;
else bracketStack.pop();
break;
case ']':
if (bracketStack.isEmpty() || bracketStack.peek() != '[') return false;
else bracketStack.pop();
break;
default:
bracketStack.push(bracket);
}
}
return bracketStack.isEmpty();
}

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for (int a0 = 0; a0 < t; a0++) {
String expression = in.next();
System.out.println( (isBalanced(expression)) ? "YES" : "NO" );
}
}
}

Hope you find this useful. Should you have any doubt don’t hesitate in asking. Any suggestion or comment will be appreciated. Thanks!

P.D. If you are looking for the solution in other programming language you can look at my C and Python implementations.