JS Solution (super easy to understand in JavaScript)


  • 0
    A

    This is the most easy to understand solution I've seen so far.

    let isValid = s => {
        var map = {
            '[': ']',
            '(': ')',
            '{': '}'
        }
        // removing everything but [](){}
        var wrappers = s.split('').filter(char => '[](){}'.includes(char))
        var openers = []
        
        var isOpener = c => !!map[c]
        var closesLastOpener = c => c == map[openers[openers.length - 1]]
        
        for (let char of wrappers) {
            if (isOpener(char)) {
                openers.push(char)
            } else if (closesLastOpener(char)) {
                openers.pop()
            }
        }
        return openers.length == 0
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.