Javascript stack solution


  • 0
    P

    Just a simple solution using stack

    /**
     * @param {string} s
     * @return {boolean}
     */
    var isValid = function(str) {
        var bracketsMap = {
            '(': ')',
            '[': ']',
            '{': '}'
        };
        
        var bracketsStack = [str[0]];
        str = str.substr(1);
    
      if (!bracketsMap[bracketsStack[0]]) {
        return false;
      }
    
      while (str.length) {
        var currentBracket = str[0];
        if (bracketsMap[currentBracket] === currentBracket) {
          if (bracketsStack[bracketsStack.length - 1] === currentBracket) {
            bracketsStack.pop();
          } else {
            bracketsStack.push(currentBracket);
          }
        } else {
          if (bracketsMap[currentBracket]) {
            bracketsStack.push(currentBracket);
          } else {
            let previousBracket = bracketsStack.pop();
            if (bracketsMap[previousBracket] !== currentBracket) {
              return false
            }
          }
        }  
        str = str.substr(1);
      }
      return bracketsStack.length ? false : true;
    };
    

  • 0
    J
    var isValid = function(s) {
        let open = ['(', '{', '['], closed = [')', '}', ']'], temp = [], validOrInvalid = true;
        s.split('').forEach(a => {
            if (open.includes(a)) {
                temp.push(a)
            } else if (closed.includes(a)) {
                const t = temp.pop()
                if (!t || closed.indexOf(a) !== open.indexOf(t)) validOrInvalid = false
            }
        })
        if (!validOrInvalid) return false
        return temp.length === 0
    };

Log in to reply
 

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