Balanced Brackets – Possible Second Attempt

I selected the next unsolved challenge at HackerRank in the section labeled Cracking the Coding Interview. If interested you may use the following URL to get to the challenge: https://www.hackerrank.com/challenges/ctci-balanced-brackets

It seems to me like I have already solved this challenge.

Following is the console of the Eclipse Neon IDE:

3

{[()]}

{[(])}

{{[[(())]]}}

YES

NO

YES

The following Java code passed the 19 test cases:

import java.util.Scanner;

import java.util.Stack;

publicclass Solution {

/*

*

*/

publicstaticboolean isBalanced(String expression) {

Stack<Character> stack = new Stack<Character>();

// **** ****

for (int i = 0; i < expression.length(); i++) {

// **** ****

char c = expression.charAt(i);

// **** ****

switch (c) {

case ‘{‘:

case ‘[‘:

case ‘(‘:

stack.push(c);

break;

default:

if (stack.isEmpty()) {

returnfalse;

}

char p = stack.pop();

if ((c == ‘}’) && (p != ‘{‘)) {

returnfalse;

}

if ((c == ‘]’) && (p != ‘[‘)) {

returnfalse;

}

if ((c == ‘)’) && (p != ‘(‘)) {

returnfalse;

}

break;

}

}

// **** check if the stack is not empty ****

if (!stack.isEmpty()) {

returnfalse;

}

// **** all is well ****

returntrue;

}

/*

*

*/

publicstaticvoid 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” );

}

}

}

If you have comments or questions regarding this or any other post in this blog, please do not hesitate and send me a message. I will respond as soon as possible and will not use your name unless you explicitly allow me to do so.