qappleh / Interview

我是追梦赤子心,公众号「深圳湾码农」的作者,某上市集团公司高级前端开发,深耕前端领域多年,每天攻破一道题,带你从0到1系统构建web全栈完整的知识体系!
https://github.com/qappleh/Interview
1.14k stars 95 forks source link

Day360:给定一个字符串str,只会出现{}()[]这6种字符,请实现一个函数isMatch(str)判断这个字符串中的括号是否是匹配的? #363

Open qappleh opened 3 years ago

qappleh commented 3 years ago

例如以下字符串均为括号匹配的:(){()[{}]} ()({}) {()}[]{()} [{{[()]}}]。

AimWhy commented 3 years ago
function isLeft (char) {
    return ({'(' : 1,  '{': 2, '[': 3})[char] || 0;
}

function isRight (char) {
    return ({')' : 1,  '}': 2, ']': 3})[char] || 0;
}

function isMatch(str) {
    let stack = [];
    let len = str.length;
    let i = 0;

    while (i < len) {
        let char = str[i];
        if (isLeft(char)) {
            stack.push(char)
        }
        let rightCode = isRight(char);
        if (rightCode) {
            if (isLeft(stack.pop()) !== rightCode) {
                return false;
            }
        }
        i++;
    }
    return !stack.length;
}

let str = '(){()[{}]}()({}){()}[]{()}[{{[()]}}]';
console.log(isMatch(str))

str = '(){()[{}]}()({}){()}[]{()}[{{[()]}}]}';
console.log(isMatch(str))
BamLin commented 3 years ago

大佬这些题是怎么弄到的呀

qappleh commented 3 years ago

大佬这些题是怎么弄到的呀

网友分享和投稿的,哈哈,欢迎分享题目哈!