NC52 有效括号序列

120 阅读1分钟

image.png

/**
 *
 * @param s string字符串
 * @return bool布尔型
 */
function isValid(s) {
    // write code here
    // 先构建一个符合条件的数组
    const truely = ["()", "[]", "{}"];

    // 用 filter+index 构建目标数组中符合条件的元素的数组
    function check() {
        const checkList = truely.filter((item) => {
            return s.indexOf(item) > -1;
        });

        return checkList.length;
    }

    // 去掉目标数组里面所有符合的字符串
    // 不用排序,有一组符合的就删除一组
    // "[[]]" true
    while (check() > 0) {
        truely.forEach((item) => {
            s = s.replace(item, "");
        });
    }

    return s.length > 0 ? false : true;
}
module.exports = {
    isValid: isValid,
};

有效括号序列_牛客题霸_牛客网 (nowcoder.com)