settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Balanced Parentheses - Java Task (Stacks)

+13 votes

Java task (with Stacks):

Given a sequence consisting of parentheses, determine whether the expression is balanced. A sequence of parentheses is balanced if every open parenthesis can be paired uniquely with a closed parenthesis 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 parenthesis.
{[(])} - This is not a balanced parenthesis.

Input Format: Each input consists of a single line, S, the sequence of parentheses.

Constraints: 
1 ≤ lens ≤ 1000, where lens is the length of the sequence. 
Each character of the sequence will be one of {, }, (, ), [, ].

Output Format: For each test case, print on a new line "YES" if the parentheses are balanced. Otherwise, print "NO". Do not print the quotes.

 

Input

Output

{[()]}

YES

{[(])}

NO

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

YES

 

asked in Java category by user mitko
edited by user golearnweb

1 Answer

+1 vote
 
Best answer

Here is the answer my friend (read the comments to understand the solution better):

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

public class Pr_07_BalancedParentheses {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        String brackets = sc.nextLine();

        Stack<Character> stack = new Stack<>();//CREATING THE stack FOR THE BRACKETS
        boolean isBalanced = true;//CHECKING WHETHER THE BRACKETS ARE BALANCED

        for (int i = 0; i < brackets.length(); i++) {//GETTING THROUGH ALL THE ELEMENTS FROM THE INPUT
            char bracket = brackets.charAt(i);//GETTING ONE SINGLE BRACKET AND PUTTING IT INTO THE char bracket
            if (bracket == '{' || bracket == '[' || bracket == '(') {//CHECKING WHETHER THE BRACKET TYPE IS THE OPENING ONE
                stack.push(bracket);//ADDING THE OPENING BRACKET INTO THE stack
            } else {
                if (bracket == '}') {
                    bracket = '{';
                } else if (bracket == ')') {
                    bracket = '(';
                } else if (bracket == ']') {
                    bracket = '[';
                }

                if (stack.empty()) {//CHECKING WHETHER THE stack IS EMPTY
                    isBalanced = false;
                    break;
                }

                if (bracket == stack.peek()) {
                    stack.pop();
                } else {
                    isBalanced = false;
                    break;
                }
            }
        }

        if (isBalanced) {
            System.out.println("YES");
        } else {
            System.out.println("NO");
        }
    }
}

 

answered by user paulcabalit
selected by user golearnweb
...