Valid Braces - CodeWars Challenge
You can use array
to keep track of previously appeared opening braces and once any closing tag appears you need to match it with the last value of array if it's matching pop the last value out of else else return false, in the end if you're left with empty array return true else return false
function validBraces(braces){
let tracer = []
for(let i=0;i < braces.length; i++){
if ( braces[i] === "(" || braces[i] === "{" || braces[i] === "["){
tracer.push(braces[i])
} else{
if(tracer.length === 0) return false
let lastValue = tracer[tracer.length-1]
if( (braces[i] === ']' && lastValue === '[') || (braces[i] === '}' && lastValue === '{') || (braces[i] === ')' && lastValue === '('))
{
tracer.pop()
} else {
break;
}
}
}
return tracer.length === 0
}
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( "({})[({})]" )) // true
console.log(validBraces( "(})" )) // false
console.log(validBraces( "(({{[[]]}}))" )) //true
console.log(validBraces( "{}({})[]" )) // true
console.log(validBraces( ")(}{][" )) // false
console.log(validBraces( "())({}}{()][][" )) // false
console.log(validBraces( "(((({{" )) // false
console.log(validBraces( "}}]]))}])" )) // false
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
function validBraces(braces){
while(/\(\)|\[\]|\{\}/g.test(braces)){braces = braces.replace(/\(\)|\[\]|\{\}/g,"")}
return !braces.length;
}
// double regex