423 · Valid Parentheses - LintCode

# Description

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.


# Example

Example 1:

Input: "([)]"
Output: False

Example 2:

Input: "()[]{}"
Output: True

Challenge

Use O(n) time, n is the number of parentheses.

# Solution

public class Solution {
    /**
     * @param s: A string
     * @return: whether the string is a valid parentheses
     */
    public boolean isValidParentheses(String s) {
        if(s.length() <= 1 || s == null){
            return false;
        }
        Stack<Character> stack = new Stack<>();
        for(int i = 0; i < s.length(); i++){
            if(s.charAt(i) == '(' || s.charAt(i) == '['|| s.charAt(i) == '{'){
                stack.push(s.charAt(i));
            } else {
                if(!stack.empty() && stack.peek() == leftOf(s.charAt(i))){
                    stack.pop();
                } else {
                    return false;
                }
            }
        }
        System.out.println(stack.size());
        return stack.empty();
           
    }
    private char leftOf(char c){
        if(c == '}') return '{';
        if(c == ')') return '(';
     return '[';
        
    }
}