Firstly I was using regex to get if the number of parentheses in a string is balanced or not, but the performance was quite slow when any large string was passed to the regex. So I created this custom method, which returns whether a string contains balanced parentheses or not. Please review this code and point out any mistakes and improvements.
checkBalancedBrackets(str) {
var b1 = [];
var b2 = [];
for ( var i=0; i < str.length; i++ ) {
var ch = str.charAt(i);
if (ch == "(" ) b1.push(ch);
else if ( ch == "[" ) b2.push(ch);
else if ( ch == ")" ) {
if (b1.length < 1) {
return false;
} else {
b1.pop();
}
}
else if ( ch == "]" ) {
if (b2.length < 1) {
return false;
} else {
b2.pop();
}
}
}
return b1.length == 0 && b2.length == 0;
}
[]()
. While[]
or()
are present in the copy, remove them. If any characters remain in the copy, the original string was not balanced. \$\endgroup\$