• + 0 comments

    java 8

    import java.util.Scanner;

    class Solution {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        char[] arr = new char[100];  
        while (sc.hasNext()) {
            String input = sc.next();
            boolean isBalanced = true;
            int top = -1;
    
            for (int i = 0; i < input.length(); i++) {
                char ch = input.charAt(i);
    
                if (ch == '(' || ch == '{' || ch == '[')
                    arr[++top] = ch; 
                else if (ch == ')' || ch == '}' || ch == ']') {
                    if (top == -1) {
                        isBalanced = false;
                        break;
                    }
                    else {
                        if (!isMatchingPair(arr[top--], ch)) {
                            isBalanced = false;
                            break;
                        }
                    }
                }
            }
            if (top != -1) {
                isBalanced = false;
            }
            System.out.println(isBalanced ? "true" : "false");
        }
        sc.close();
    }
    
    static boolean isMatchingPair(char open, char close) {
        return (open == '(' && close == ')') ||
               (open == '{' && close == '}') ||
               (open == '[' && close == ']');
    }
    

    }