Monday, May 29, 2017

Parenthesis Check in Java

import java.util.Stack;

public class ParenthesisCheck {
    public static void main(String[] args) {
        System.out.println("4: "+CheckParentesis("4"));
        System.out.println("{[}]: "+CheckParentesis("{[}]"));
        System.out.println("({[]}): "+CheckParentesis("({[]})"));
        System.out.println("[): "+CheckParentesis("[)"));
        System.out.println("(()){}(): "+CheckParentesis("(()){}()"));
        System.out.println("){}): "+CheckParentesis("){})"));
    }
    public static boolean CheckParentesis(String str) {
        if(str.isEmpty())
            return true;

        Stack<Character> stack = new Stack<Character>();
        for(int i=0; i<str.length(); i++) {
            char current = str.charAt(i);
            if(current=='{' || current=='(' || current=='[') {
                stack.push(current);
            }
            if(current=='}' || current==')' || current==']') {
                if(stack.isEmpty()) 
                    return false;
                char last = stack.peek();
                if(current=='}' && last=='{' || current==')' && last=='('|| current==']' && last=='[')
                    stack.pop();
                else 
                    return false;
            }
        }
        return stack.isEmpty();
    }
}

//Output:
4: true
{[}]: false
({[]}): true
[): false
(()){}(): true
){}): false

No comments:

Post a Comment