20. Valid Parentheses


Problem

https://leetcode.com/problems/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.

Solution

Stack.

/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function(s) {
    if (typeof s !== 'string') {
        s = s.toString()
    }

    let stack = []
    for (let i = 0; i < s.length; i += 1) {
        switch (s[i]) {
            case '{':
                stack.push('}')
                break
            case '[':
                stack.push(']')
                break
            case '(':
                stack.push(')')
                break
            default:
                if (stack.pop() !== s[i]) {
                    return false
                }
        }
    }

    if (stack.length === 0) {
        return true
    }

    return false
};

results matching ""

    No results matching ""