function isBracketsBalanced(str) {
const stack = [];
const openBracket = '{';
const closeBracket = '}';
for (let i = 0; i < str.length; i++) {
const char = str[i];
if (char === openBracket) {
stack.push(char);
} else if (char === closeBracket) {
if (stack.length === 0) {
return false; // Unmatched closing bracket
}
stack.pop();
}
}
return stack.length === 0; // True if all brackets are matched
}
// Example usage:
console.log(isBracketsBalanced("{abc}")); // true
console.log(isBracketsBalanced("{abc{def}}")); // true
console.log(isBracketsBalanced("{{abc}")); // false
console.log(isBracketsBalanced("{abc}}")); // false
console.log(isBracketsBalanced("{abc}def{ghi}")); // true
console.log(isBracketsBalanced("}abc{")); // false
console.log(isBracketsBalanced("")); // true - Empty string is considered balanced
console.log(isBracketsBalanced("abc")); // true - No brackets are also considered balanced
// More robust version handling other bracket types ((), [], {})
function isAllBracketsBalanced(str) {
const stack = [];
const brackets = {
'(': ')',
'[': ']',
'{': '}',
};
for (let char of str) {
if (brackets[char]) {
// If it's an opening bracket, push it onto the stack
stack.push(char);
} else {
// If it's a closing bracket
const lastOpened = stack.pop();
if (!lastOpened || brackets[lastOpened] !== char) {
// If the stack is empty or the closing bracket doesn't match the last opened one
return false;
}
}
}
// If the stack is empty at the end, all brackets are balanced
return stack.length === 0;
}
console.log("---- All bracket types ----");
console.log(isAllBracketsBalanced("(){}[]")); // true
console.log(isAllBracketsBalanced("([{foo}])")); // true
console.log(isAllBracketsBalanced("{[}]")); // false
console.log(isAllBracketsBalanced("[(])")); // false
This code uses a stack data structure to keep track of opening brackets. When a closing bracket is encountered, it's checked against the top of the stack. If they match, the opening bracket is popped off the stack. If they don't match or the stack is empty when a closing bracket is found, the brackets are unbalanced. If the stack is empty at the end of the string, all brackets are balanced.
The second, more robust function, isAllBracketsBalanced
, handles parentheses ()
, square brackets []
, and curly braces {}
using a lookup table (brackets
) for efficient matching. This is generally more useful in real-world scenarios.