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 with left array, i don't make check brackets here {[(3+1)+2]+}
. And if reverse like now, then i fail to check here [1+1]+(2*2)-{3/3}
function brackets(expression){
let leftArr=[];
let rightArr = [];
for(let i=0; i<expression.length; i++){
if(expression[i] === '(' || expression[i] === '[' || expression[i] === "{"){
leftArr.push(expression[i]);
}
if(expression[i] === ')'){
rightArr.push("(");
}else if(expression[i] === '}'){
rightArr.push("{");
} else if(expression[i] === ']'){
rightArr.push("[");
}
}
rightArr.reverse();
if(leftArr.length<rightArr.length || leftArr.length>rightArr.length){
return false;
}
for(let k=0; k<leftArr.length; k++) {
if(leftArr[k] != rightArr[k]){
return false;
}
}
return true;
}
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
(3+{1-1)}
– Aseptic