【算法】JS匹配有效括号

//匹配有效括号
function areParenthesesValid(input) {
    let stack = [];
    const mapping = {
        '(': ')',
        '{': '}',
        '[': ']',
    };
    for (let i = 0; i < input.length; i++) {
        const char = input[i];
        // 如果是开括号,将对应的闭合括号入栈
        if (char in mapping) {
            stack.push(mapping[char]);
        } else {
            // 如果是闭合括号,则尝试从栈中弹出匹配的开括号
            const expected = stack.pop();
            if (expected !== char) {
                // 如果弹出的不是匹配的括号,则直接返回false
                return false;
            }
        }
    }
    // 最后检查栈是否为空,如果为空则说明所有的括号都正确闭合了
    return stack.length === 0;
}
// 使用示例
console.log(areParenthesesValid('({})')); // true
console.log(areParenthesesValid('({[})]')); // false
console.log(areParenthesesValid('({}[])')); // true

你可能感兴趣的:(html5,javascript,html)