首页 > 解决方案 > 检查字符串在语法上是否为真

问题描述

我正在尝试使用正则表达式解决任务。给定一个带有字符串参数的函数。字符串包含(){}<>[]大括号。我必须检查字符串在语法上是否正确,并且还应该计算大括号嵌套的数量。这是我的版本(不完整)`

const checkBraces = (str) => {
  const newStr = str.replace(/[^(){}<>[\]]+/gi, '');
  let answer = newStr.match(/\(+\)+|\<+\>+|\{+\}+|\[+\]+/g);
  console.log(answer);
}

这是函数 ` 的最小测试次数

checkBraces("---(++++)----") == 0
checkBraces("") == 0
checkBraces("before ( middle []) after ") == 0
checkBraces(") (") == 1
checkBraces("} {") == 1
checkBraces("<(   >)") == 1
checkBraces("(  [  <>  ()  ]  <>  )") == 0
checkBraces("   (      [)") == 1

如果存在 en 错误,则该函数应返回 1 ,否则返回 0 。在我的函数中,我首先尝试替换所有non-braces,所以我有一个清晰的字符串。现在我无法解决这个问题。

标签: javascriptstringparsing

解决方案


您可以通过遍历字符串并保留一堆左大括号来解决此问题。每次找到右大括号时,从堆栈中弹出。右大括号应与您弹出的东西相匹配,否则它们不平衡。最后堆栈应该是空的:

let braces = { // lookup to match closing with opening
    '(':')',
    '{':'}',
    '<':'>',
    '[':']'
}
let closing = new Set([')', '}', '>', ']']) // quick lookup of brackets
let opening = new Set(['(', '{', '<', '['])

function checkBraces(str) {
    /* returns true if balanced, false if unbalanced */
    let stack = []
    for (l of str){
        if (closing.has(l)){                            // found a closing bracket
            if (l !== braces[stack.pop()]) return false // does it match the last opening?
        } else if(opening.has(l)) stack.push(l)         // found an opening push to the stack
    }
    return stack.length === 0 
}
console.log(checkBraces("before ( middle []) after "))
console.log(checkBraces("<(   >)"))
console.log(checkBraces("(  [  <>  ()  ]  <>  )"))
console.log(checkBraces("   (      [)"))
console.log(checkBraces(" )"))
console.log(checkBraces(" <"))


推荐阅读