写一个方法判断大括号{}是否闭合

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.

posted @   王铁柱6  阅读(3)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示