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;
    };
    

Log in to reply
 

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