Javascript String Validate Braces

Introduction

Determines if the order of the braces is valid.

It should return true if the string is valid, and false if it's invalid.

All input strings will be nonempty, and will only consist of parentheses, brackets and curly braces: ()[]{}.

A string of braces is considered valid if all braces are matched with the correct brace.

"(){}[]"   =>  True
"([{}])"   =>  True
"(}"       =>  False
"[(])"     =>  False
"[({})](]" =>  False

function validBraces(parens) {
  const stack = [];/*  w w  w  .j a v a  2s  . com*/

  const braces = {
    "(": { isOpen: true },
    "[": { isOpen: true },
    "{": { isOpen: true },
    ")": { match: "(" },
    "]": { match: "[" },
    "}": { match: "{" },
  };

  for (let i = 0; i < parens.split("").length; i++) {
    const braket = braces[parens[i]];
    if (braket.isOpen === true) {
      stack.push(parens[i]);
    }
    else if (stack.pop() !== braket.match) {
      return false;
    }
  }

  return stack.length === 0;
}

const input = "[()]";
console.log(validBraces(input));



PreviousNext

Related