# NC52 有效括号序列

https://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2 (opens new window)

# 描述

给出一个仅包含字符'(',')','{','}','['和']',的字符串,判断给出的字符串是否是合法的括号序列
括号必须以正确的顺序关闭,"()"和"()[]{}"都是合法的括号序列,但"(]"和"([)]"不合法。

示例1:

输入:
"["

返回值:
false

示例2:

输入:
"[]"

返回值:
true

# 解答


/**
  * 遍历 s
  * 左括号进栈
  * 右括号,出栈,出栈的标记如果跟当前右括号不匹配则非法
  * 遍历完,栈未空则说明有未匹配的,非法
  * @param s string字符串 
  * @return bool布尔型
  */
function isValid( s ) {
    const items = s.split('');
    const startTagStack = [];

    if (items.length % 2 !== 0) {
        return false;
    }

    const isMatch = (startTag) => {
        return startTagStack.pop() === startTag;
    }

    for (let i = 0, len = items.length; i < len; i++) {
        const item = items[i];

        switch(item) {
            case '(':
            case '[':
            case '{': startTagStack.push(item); break;

            case ')': {
                if (!isMatch('(')) {
                    return false
                } 
                break;
            }
            case ']': {
                if (!isMatch('[')) {
                    return false
                } 
                break;
            }
            case '}': {
                if (!isMatch('{')) {
                    return false
                } 
                break;
            }
        }
    }

    if (startTagStack.length !== 0) {
        return false;
    }

    return true;
}

module.exports = {
    isValid : isValid
};
本章目录