Balanced parentheses

Problem: Check if given sequence of parenthesis is a balanced parenthesis. This question was asked in HackerRank.

Given a sequence consisting of parentheses, determine whether the expression is balanced. A sequence of parentheses is balanced if every open parentheses can be paired uniquely with a closed parentheses that occurs after the former. Also, the interval between them must be balanced. You will be given three types of parentheses: (, {, and [.
{[()]} – This is a balanced parentheses.
{[(])} – This is not a balanced parentheses.

Sample Input
3
{[()]}
{[(])}
{{[[(())]]}}

Sample Output
YES
NO
YES

Java code:

import java.util.Scanner;
import java.util.Stack;

public class ValidateExpressionTest {

	static final String YES = "YES";
	static final String NO = "NO";
	
	private static String validateExpression(String expression) {

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

		for (int i = 0; i < expression.length(); i++) {
			char ch = expression.charAt(i);
			switch (ch) {
			case '{':
			case '[':
			case '(':
				stack.push(ch);
				break;
			case '}':
				if (stack.isEmpty() || stack.pop() != '{')
					return NO;
				break;
			case ']':
				if (stack.isEmpty() || stack.pop() != '[')
					return NO;
				break;
			case ')':
				if (stack.isEmpty() || stack.pop() != '(')
					return NO;
				break;
			default:
				return NO;
			}
		}

		return stack.isEmpty() ? YES : NO;
	}

	public static void main(String[] args) {
		
		Scanner in = new Scanner(System.in);

		int numberOfTestCases = Integer.parseInt(in.nextLine());
		String[] expressions = new String[numberOfTestCases];
		for (int i = 0; i < numberOfTestCases; i++) {
			expressions[i] = in.nextLine();
		}

		for (int i = 0; i < numberOfTestCases; i++) {
			System.out.println(validateExpression(expressions[i]));
		}

		in.close();
	}
}

I hope you liked the solution.
Please comment for any questions.

Leave a Reply