Thursday, 19 August 2021

Balanced Parentheses

 package demoTest;


import java.util.Stack;


public class test {

    // Function to check if the given expression is balanced or not

    public static boolean balParenthesis(String exp)

    {

        // base case: length of the expression must be even

        if (exp.length() % 2 == 1) {

            return false;

        }

 

        // take an empty stack of characters

        Stack<Character> stack = new Stack();

 

        // traverse the input expression

        for (char ch: exp.toCharArray())

        {

            // if the current character in the expression is an opening brace,

            // push the corresponding closing brace into the stack.

            if (ch == '(') {

                stack.push(')');

            }

            else if (ch == '{') {

                stack.push('}');

            }

            else if (ch == '[') {

                stack.push(']');

            }

 

            // return false if the popped character is not the same as the

            // current character

            else if (stack.isEmpty() || stack.pop() != ch) {

                return false;

            }

        }

 

        // the expression is balanced only when the stack is empty at this point

        return stack.empty();

    }

 

    public static void main(String[] args)

    {

        String exp = "{([)}[{}]";

 

        if (balParenthesis(exp)) {

            System.out.println("The expression is balanced");

        }

        else {

            System.out.println("The expression is not balanced");

        }

    }

}



No comments:

Post a Comment