• + 0 comments

    My Solution: import java.util.*; class Solution{ public static void main(String[] argh) { Scanner sc = new Scanner(System.in);
    while (sc.hasNext()) { String input=sc.next(); //Complete the code //check if input string is balanced boolean isBalanced = isBalanced(input);

                        //Print the result true or false
            if(isBalanced)
            {
                System.out.println("true");
            }
            else
            {
            System.out.println("false");
            }
    
        }
        sc.close(); 
    }
        // Method to check if a string containing parentheses, brackets, and braces is balanced
    
        public static boolean isBalanced(String s)
        {
                    // Initialize a stack to hold opening symbols
            Stack<Character>stack = new Stack<>();
    
                        // Iterate through each character in the string
            for(char ch : s.toCharArray())
            {
                            // If the character is an opening symbol, push it onto the stack
                if(ch == '(' || ch == '{' || ch == '[')
                {
                    stack.push(ch);
                }
                                 // If the character is a closing symbol
                else if(ch == ')' || ch == '}' || ch == ']')
                {
                                // Check if the stack is empty
                    if(stack.isEmpty())
                    {
                        return false; // Unmatched closing symbol
                    }
                                        // Pop the top element from the stack
                    char top = stack.pop();
                                         // Check if the top element matches the closing symbol
                    if(!isMatchingPair(top, ch))
                    {
                        return false; // Mismatched pair
                    }
                }
            }
                        // The string is balanced if the stack is empty at the end
            return stack.isEmpty();
        }
    
         // Method to check if the opening and closing symbols match
        public static boolean isMatchingPair(char open, char close)
        {
            return(open == '(' && close == ')')||
                    (open == '{' && close == '}')||
                    (open == '[' && close == ']');
        }
    }