Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Valid Braces - CodeWars Challenge

There is a challenge on codewars that asks you to check whether a string of parentheses, brackets, and curly braces is valid.

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

I.e. "()" is valid and "[(])" is not.

"(){}[]" is valid and "[({})](]" is not. Etc.

I've been able to create some logic to check for whether or not there are the right number of opening and closing braces.

ATTEMPT:

function validBraces(braces) {

  let parenCount = 0;
  let squareBracketCount = 0;
  let curlyBraceCount = 0;

    for (let i =0; i < braces.length; i++) {
      let character = braces[i];
        if (character === "(") {
          parenCount -= 1;
          }
        if (character === ")") {
          parenCount += 1;
          }
        if (character === "[") {
          squareBracketCount -= 1;
          }
        if (character === "]") {
          squareBracketCount += 1;
        }
        if (character === "{") {
          curlyBraceCount -= 1;
        }
        if (character === "}") {
          curlyBraceCount += 1;
        }
      }
      if (parenCount === 0 && squareBracketCount === 0 && curlyBraceCount === 0) {
        return true;
      } 
      else {
        return false;
      }
}

But I've not been able to come up with a way to check for whether or not the opening brace "closes" before the next type of brace opens.

Maybe something like this?

if (
  (firstChar === "(" && lastChar === ")") ||
  (firstChar === "{" && lastChar === "}") ||
  (firstChar === "[" && lastChar === "]")
) {
  return true;
} else {
  return false;
}

But then this would have to be checked in accordance with my other if-statement...(?)

EDIT: Key to understanding this challenge is that the closing brace must either come directly after the opening brace or it must be "parallel" - in symmetry with the other.

like image 302
HappyHands31 Avatar asked Feb 03 '23 18:02

HappyHands31


1 Answers

You don't really need to use arrays here, you can just use regex and recursion:

const regex = /\(\)|\[\]|\{\}/;
const validBraces = braces => regex.test(braces)
  ? validBraces(braces.replace(regex, ''))
  : '' === braces

console.log(validBraces('{{}}')) // true
console.log(validBraces('{{[]}}')) // true
console.log(validBraces('{[{}]}')) // true
console.log(validBraces('({{}})')) // true
console.log(validBraces('{[()]}')) // true
console.log(validBraces('{{}[}')) // false
console.log(validBraces('{{]}}')) // false
console.log(validBraces('{}}')) // false
console.log(validBraces('{({}}')) // false
console.log(validBraces('((}}')) // false
console.log(validBraces('}[)}')) // false
like image 200
Mike K Avatar answered Feb 06 '23 08:02

Mike K