Skip to content

Latest commit

 

History

History
50 lines (39 loc) · 1.34 KB

File metadata and controls

50 lines (39 loc) · 1.34 KB

Challenge Title : Stack-queue-brackets

Whiteboard Process

Whiteboard Link stack-queue-brackets


Solution

function validateBrackets(str) {
  const stack = [];
  const opBr = "([{";
  const clBr = ")]}";

  for (let i = 0; i < string.length; i++) {
    const bracket = string[i];

    if (opBr.includes(bracket)) {
      stack.push(bracket);
    } else if (clBr.includes(bracket)) {
      if (stack.length === 0) {
        return false;
      }

      const correspondingOpeningBracket = opBr[clBr.indexOf(bracket)];
      if (stack.pop() !== correspondingOpeningBracket) {
        return false;
      }
    }
  }

  return stack.length === 0;
}

Tests

console.log(validateBrackets("{}")); // Output: true
console.log(validateBrackets("{}(){}")); // Output: true
console.log(validateBrackets("()[[Extra Characters]]")); // Output: true
console.log(validateBrackets("(){}[[]]")); // Output: true
console.log(validateBrackets("{}{Code}[Fellows](())")); // Output: true
console.log(validateBrackets("[({}]")); // Output: false
console.log(validateBrackets("(](")); // Output: false
console.log(validateBrackets("{(})")); // Output: false