20. 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.

/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function(s) {
    var stack=[];
    var len=s.length;
    if(s[0]==')'||s[0]==']'||s[0]=='}')
    {
        return false;
    }
    else 
    {
        for(var i=0;i<len;i++)
        {
            if(s[i]==')')
            {
                if(stack[stack.length-1]=='(')
                {
                    stack.pop();
                }
                else
                {
                    return false;
                }
            }
            else if(s[i]==']')
            {
                if(stack[stack.length-1]=='[')
                {
                    stack.pop();
                }
                else
                {
                    return false;
                }
            }
            else if(s[i]=='}')
            {
                if(stack[stack.length-1]=='{')
                {
                    stack.pop();
                }
                else
                {
                    return false;
                }
            }
            else {
                stack.push(s[i]);}
        }
    }
    if(stack.length==0)
    {
        return true;
    }
    else
    {
        return false;
    }
    
};

 

posted on 2016-05-01 13:47  baiyuhong  阅读(94)  评论(0)    收藏  举报