JSFiddle - React, Tailwind, and code Playground
by Prathameshsb
JavaScript
/*
Given a string possibly containing three types of braces ({}, [], ()),
write a function that returns a Boolean indicating whether the given string contains a
valid nesting of braces.
*/
const validate = (str) => {
// return false or true;
const stack = [];
const pair = {
'}': '{',
']': '[',
')': '('
}
for(let char of str) {
if(char === '{' || char === '[' || char === '(') {
stack.push(char);
}else if(char === '}' || char === ']' || char === ')') {
if(stack.pop() !== pair[char]) {
return false;
}
}
}
return stack.length === 0;
}
console.log(validate('{{([])}}') === true ? 'pass' : 'fail'); //true
console.log(validate('{([)}}') === false ? 'pass' : 'fail'); //false
console.log(validate(']') === false ? 'pass' : 'fail'); //
console.log(validate('{123()4}[]') === true ? 'pass' : 'fail');
console.log(validate('{()[]}') === true ? 'pass' : 'fail');
console.log(validate('{[]}]()') === false ? 'pass' : 'fail');