Parenthesis matching program


import java.util.Stack;
import java.util.EmptyStackException;
import java.util.Optional;

class ParenthesisMatching {
    static boolean isBalanced(Optional equationOptional) {
        // if input is null or empty return false
        if(!equationOptional.isPresent()) {
            return false;
        }
        // convert string to char array
        char[] chars = equationOptional.get().toCharArray();
        // create stack 
        Stack stack = new Stack<>();
        for(char ch : chars) {
            try {
                if(ch == '(') {
                    stack.push('(');
                } else if(ch == ')') {
                    stack.pop(); // return throws EmptyStackException if stack is empty
                }
            } catch(EmptyStackException e) {
                return false;
            }
        }
        return stack.empty() ? true : false;
    }
    public static void main(String[] args) {
        // positive case 
        String str = "(a+b)*(c-d)";
        Optional equationOptional = Optional.of(str);
        System.out.println("Is " + str + " balanced? " + isBalanced(equationOptional));
        
        // negative case 
        str = "((a+b)*(c-d)";
        equationOptional = Optional.of(str);
        System.out.println("Is " + str + " balanced? " + isBalanced(equationOptional));
        
        // negative case 
        str = "(a+b)*(c-d))";
        equationOptional = Optional.of(str);
        System.out.println("Is " + str + " balanced? " + isBalanced(equationOptional));
    }
}

Outpur
Is (a+b)*(c-d) balanced? true
Is ((a+b)*(c-d) balanced? false
Is (a+b)*(c-d)) balanced? false

Comments

Popular posts from this blog

SQL basic interview question

gsutil Vs Storage Transfer Service Vs Transfer Appliance