javascript - 检查字符串在语法上是否为真
问题描述
我正在尝试使用正则表达式解决任务。给定一个带有字符串参数的函数。字符串包含(){}<>[]
大括号。我必须检查字符串在语法上是否正确,并且还应该计算大括号嵌套的数量。这是我的版本(不完整)`
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
,所以我有一个清晰的字符串。现在我无法解决这个问题。
解决方案
您可以通过遍历字符串并保留一堆左大括号来解决此问题。每次找到右大括号时,从堆栈中弹出。右大括号应与您弹出的东西相匹配,否则它们不平衡。最后堆栈应该是空的:
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(" <"))
推荐阅读
- powerbi - 在关系的多方面访问相关值
- java - 在java中使用Scanner类递归获取字符串用户输入
- react-native - React Native 移动应用程序 - 国际化图像的最佳方法
- c# - 如何在 .net 核心中使用用户传递的用户名和密码作为 DbContext 的凭据?
- date - 我可以仅使用 url 打开特定日期和时间范围的交易视图图表吗?
- c# - 如何将 JsonProperty 附加到另一个 JsonProperty
- eslint - 如何关闭对象速记
- odoo - 不知道如何导入 one2many 和 many2one 模型
- python - 动态加载“whl”模块
- list - kotlin:确定 2 个列表是否有任何共同元素的最佳方法是什么?