Skip to content

Latest commit

 

History

History
32 lines (30 loc) · 680 Bytes

File metadata and controls

32 lines (30 loc) · 680 Bytes

/**
 * T(n): O(n)
 * S(n): O(n)
 */
function isValid(s: string): boolean {
    const mapping = {
        '(': ')',
        '{': '}',
        '[': ']'
    }
    const stack = []

    for (const c of s) {
        if (Object.keys(mapping).includes(c)) {
            stack.push(c)
        } else if (Object.values(mapping).includes(c)) {
            if (stack.length === 0 || mapping[stack.pop()] !== c) {
                return false
            }
        }
    }

    return stack.length === 0
};

队列