检查字符串是否在语法上是真的

Nor*_*yan 1 javascript string parsing

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

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

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

checkBraces("---(++++)----") == 0
checkBraces("") == 0
checkBraces("before ( middle []) after ") == 0
checkBraces(") (") == 1
checkBraces("} {") == 1
checkBraces("<(   >)") == 1
checkBraces("(  [  <>  ()  ]  <>  )") == 0
checkBraces("   (      [)") == 1
Run Code Online (Sandbox Code Playgroud)

如果出现错误,则函数应返回1,否则为0.在我的函数中,我首先尝试替换所有,non-braces所以我有一个明确的字符串.现在我无法解决这个问题.

Mar*_*yer 6

你可以通过迭代字符串并保持一堆开口括号来解决这个问题.每次找到右括号时,都会从堆栈中弹出.闭合支撑应该与您弹出的东西相匹配或者它们不平衡.最后堆栈应为空:

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(" <"))
Run Code Online (Sandbox Code Playgroud)