Valid Parentheses

Jan 22, 2018

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.

 

var isValid = function(s) {
    paren = [];
    for(var i=0; i<s.length; i++) {
        switch(s.charAt(i)) {
            case '(' :
                paren.push(')');
                break;
            case '{' :
                paren.push('}');
                break;
            case '[' :
                paren.push(']');
                break;
            default:
                if(paren.pop() !== s.charAt(i)) {
                    return false;
                }
            break;
        }
    }
    if(paren.length>0) return true;
}