• + 0 comments
    import java.util.*;
    class Solution {
        
        public static void main(String[] argh) {
            Scanner sc = new Scanner(System.in);
            while (sc.hasNext()) {
                String input = sc.next();
                // Create stack to track opening brackets
                Stack<Character> stack = new Stack<>();
                // Loop through the characters of the string
                boolean isValid = true; // Track if the string is valid
                for (int i = 0; i < input.length(); i++) {
                    Character ch = input.charAt(i);
                    
                    // If it's an opening bracket, push to the stack
                    if (ch == '{' || ch == '(' || ch == '[') {
                        stack.push(ch);
                    } 
                    // If it's a closing bracket
                    else if (ch == '}' || ch == ')' || ch == ']') {
                        // If stack is empty, it's an unmatched closing bracket
                        if (stack.isEmpty()) {
                            isValid = false;
                            break; // Exit the loop early
                        }
                        // Pop from stack and check if the brackets match
                        char top = stack.pop();
                        if ((ch == '}' && top != '{') || 
                            (ch == ')' && top != '(') || 
                            (ch == ']' && top != '[')) {
                            isValid = false;
                            break; // Exit the loop early
                        }
                    }
                }
                
                // After processing all characters, the stack must be empty
                if (isValid && stack.isEmpty()) {
                    System.out.println("true");
                } else {
                    System.out.println("false");
                }
            }
        }
    }