LeetCode 20: Valid Parentheses

May. 7, 2021

Here is my solution to this problem in PHP:

/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function(s) {
    const stack = [];
    const brackets = {
        '(': ')',
        '{': '}',
        '[': ']'
    };

    for (i=0; i<s.length; i++) {
        if (s.length === 0) return true;

        const c = s[i];
        if (brackets[c]) {
            stack.push(c);
        } else {
            const lastBracket = stack.pop();
            if (brackets[lastBracket] !== c) return false;
        }
    }

    if (stack.length > 0) return false;

    return true;
};