流浪のwolf

卷帝

导航

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 2024-06-05 14:53  流浪のwolf  阅读(4)  评论(0编辑  收藏  举报