Valid Parentheses

Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[‘ and ‘]’, determine if the input string is valid.

The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.


public class Solution {
    public boolean isValid(String s) {
        //since cases like "([])" also counts -> use stack 
        Stack<Character> stack = new Stack<Character> (); 
        int len = s.length(); 
        if (s == null || len == 0) return true; 
        if (len%2 != 0) return false; 
        for (int i = 0; i < len; i++) {
            char cur = s.charAt(i); 
            if (cur == '(' || cur == '{' || cur == '[' ) 
                stack.push(cur);
            else if (cur == ')' && !stack.empty() && stack.peek() == '(')
                stack.pop(); 
            else if (cur == '}' && !stack.empty() && stack.peek() == '{')
                stack.pop(); 
            else if (cur == ']' && !stack.empty() && stack.peek() == '[')
                stack.pop();
            else 
                return false; 
        }
        return stack.empty();
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s