Interview icon indicating copy to clipboard operation
Interview copied to clipboard

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

Open qappleh opened this issue 4 years ago • 3 comments

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

qappleh avatar Apr 09 '21 02:04 qappleh

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))

AimWhy avatar Apr 09 '21 04:04 AimWhy

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

BamLin avatar Apr 09 '21 09:04 BamLin

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

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

qappleh avatar Apr 12 '21 02:04 qappleh