流浪のwolf

卷帝

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

js有效括号匹配

复制代码
// 定义一个括号映射
const bracketMap = [
    {
        left: '[', 
        right: ']'
    },
    {
        left: '<',
        right: '>'
    },
    {
        left: '(',
        right: ')'
    },
    {
        left: '',
        right: ''
    },
    {
        left: '',
        right: ''
    },
    {
        left: '',
        right: ''
    },
    {
        left: '{',
        right: '}'
    }
]
function match(params) {
    const stack = [];
    const leftMap = bracketMap.map(item => item.left);
    const rightMap = bracketMap.map(item => item.right);
    // 将字符串形式的括号集合转为数组
    const arr = params.split('');
    // 循环每一个括号,并做判断
    for (const key in arr) {
        // 左括号入栈
        if (leftMap.includes(arr[key])) {
            stack.push(arr[key]);
        }
        // 右括号 && 右括号在映射中的下标等于栈顶括号(栈顶括号:是左括号,因为只有左括号执行了进入栈操作)在映射中的下标,说明括号匹配,那么执行出栈操作
        else if (rightMap.includes(arr[key]) && (bracketMap.findIndex(item => item.right === arr[key]) === bracketMap.findIndex(item => item.left === stack[stack.length - 1]))) {
            stack.pop(arr[key]);
        }
        // 在循环中未结束,栈为空,匹配失败
        else (!stack.length) {
            return 'ERROR';
        }
    }
    // 最后判断,栈为空,则表示匹配成功;反之,则匹配失败
    return stack.length ? 'ERROR' : 'SUCCESS';
}
// 测试case:
const str = '[<(《》【】(([【[[]]《》】()])))>]'; // true
// const str = '(){}[]';                        //  true
// const str = '([{}])';                        //  true
// const str = '(}';                            //  false
// const str = '[(])';                          //  false
// const str = '[({})](]';                      //  false
console.log(match(str));
复制代码

 

posted on   朱龙旭的网络  阅读(19)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· Blazor Hybrid适配到HarmonyOS系统
· 支付宝 IoT 设备入门宝典(下)设备经营篇
· 万字调研——AI生成内容检测
· 解决跨域问题的这6种方案,真香!
· 一套基于 Material Design 规范实现的 Blazor 和 Razor 通用组件库
点击右上角即可分享
微信分享提示