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;

public class Solution {

/*

*

*/

public static boolean 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()) {

return false;

}

char p = stack.pop();

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

return false;

}

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

return false;

}

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

return false;

}

break;

}

}

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

if (!stack.isEmpty()) {

return false;

}

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

return true;

}

/*

*

*/

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

}

}

}

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.

John

john.canessa@gmail.com

Follow me on Twitter:  @john_canessa

Leave a Reply

Your email address will not be published. Required fields are marked *