Need to find open and closed bracket, if the sequence of opening and closing brackets is violated, then return false.
But if don\'t revert right array to compare wit
Right now you are getting every single open bracket into one array, then pushing an open bracket for every closing one into another array, then comparing them. That's a bit wasteful.
Instead, you can maintain a stack. Push an open tag onto the stack and if you find a close bracket - pop from the stack
function brackets(expression) {
let stack = [];
let current;
const matchLookup = {
"(": ")",
"[": "]",
"{": "}",
};
for (let i = 0; i < expression.length; i++) {
current = expression[i]; //easier than writing it over and over
if (current === '(' || current === '[' || current === "{") {
stack.push(current);
} else if (current === ')' || current === ']' || current === "}") {
const lastBracket = stack.pop();
if (matchLookup[lastBracket] !== current) { //if the stack is empty, .pop() returns undefined, so this expression is still correct
return false; //terminate immediately - no need to continue scanning the string
}
}
}
return stack.length === 0; //any elements mean brackets left open
}
console.log(brackets('(3+{1-1)}')); // false
console.log(brackets('{[(3+1)+2]+}')); //true
console.log(brackets('[1+1]+(2*2)-{3/3}')); //true
console.log(brackets('(({[(((1)-2)+3)-3]/3}-3)')); //false
I have used an object to lookup the values but it need not be one. An alternative is to use two arrays that you have to keep in sync
opening = ["(", "[", "{"]
closing = [")", "]", "}"]
On the other hand, if you have those, you can shorten your if checks to if (open.includes(current)) and if (closing.includes(current)).