写一个方法判断大括号{}是否闭合
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.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了