lintcode-easy-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 {
    /**
     * @param s A string
     * @return whether the string is a valid parentheses
     */
    public boolean isValidParentheses(String s) {
        // Write your code here
        
        if(s == null || s.length() == 0)
            return true;
        
        Stack<Character> stack = new Stack<Character>();
        
        int length = s.length();
        
        for(int i = 0; i < s.length(); i++){
            char c = s.charAt(i);
            
            if(c == '(' || c == '[' || c == '{'){
                stack.push(c);
            }
            else{
                if(c == ')'){
                    if(stack.isEmpty() || stack.pop() != '(')
                        return false;
                }
                else if(c == ']'){
                    if(stack.isEmpty() || stack.pop() != '[')
                        return false;
                }
                else{
                    if(stack.isEmpty() || stack.pop() != '{')
                        return false;
                }
            }
        }
        
        if(stack.isEmpty())
            return true;
        else    
            return false;
    }
}

 

posted @ 2016-03-10 09:23  哥布林工程师  阅读(139)  评论(0编辑  收藏  举报