JavaScript判断括号是否闭合

这段代码定义了一个名为isCloseed的函数,用于检查一个字符串中的括号是否正确闭合。它支持多种类型的括号,并通过堆栈数据结构来验证括号的配对。当所有括号正确闭合时,函数返回true,否则返回false。示例中,函数成功地验证了'{{}

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  // 判断标签是否闭合
function isCloseed(params, keyCollection = [['{','}'],['[',']'],['(',')'],['<','>']]) {
  const array = params.split('');
  // 过滤掉不符合要求的单括号
  keyCollection = keyCollection.filter(item=> Array.isArray(item) && item.length === 2)
  if (!array.length || !keyCollection.length) return
  const keyObj = {}
  const stack = []
  const leftKey = []
  const rightKey = []
  for (let i = 0; i < keyCollection.length; i++) {
    const [left,right] = keyCollection[i];
    let courrentIndex = i
    keyObj[left] = courrentIndex + 1
    keyObj[right] = -(courrentIndex + 1)
    leftKey.push(left)
    rightKey.push(right)
  }
  for (let index = 0; index < array.length; index++) {
    const element = array[index];
    if(keyObj.hasOwnProperty(element) && leftKey.includes(element)) {
      stack.push(keyObj[element])
    }else if(keyObj.hasOwnProperty(element) && rightKey.includes(element)) {
      const currentKeyObj = keyObj[element]
      const currentLength = stack.length
      if(currentLength>0 && stack[currentLength -1] + currentKeyObj === 0) {
        stack.pop()
      } else {
        stack.push(currentKeyObj)
      }
    }
  }
  return stack.length === 0
}

isCloseed('{{}[()]}<>') // true
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值