题解 | #合法的括号字符串#

合法的括号字符串

https://www.nowcoder.com/practice/eceb50e041ec40bd93240b8b3b62d221

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param s string字符串 
 * @return bool布尔型
 */
function isValidString( s ) {
    // write code here
    // let stack = [];
    // for(const ch of s) {
    //     if(ch === '(') {
    //         stack.push('(')
    //     } else if(ch === ')') {
    //         if(stack.length === 0) return false;
    //         const index = stack.lastIndexOf('(');
    //         if(index !== -1) {
    //             stack.splice(index, 1);
    //         } else {
    //             stack.pop();
    //         }
    //     } else if(ch === '*') {
    //         stack.push('*')
    //     }
    // }
    // let leftCount = 0;
    // for(const ch of stack) {
    //     if(ch === '(') {
    //         leftCount++
    //     } else {
    //         leftCount ? leftCount-- : leftCount = 0;
    //     }
    // } 
    // return leftCount === 0;
    // (*(**))(()



    let minCount = 0;
    let maxCount = 0;

    for(const ch of s) {
        if(ch === '(') {
            minCount++;
            maxCount++;
        }else if(ch === ')') { 
            if(maxCount === 0) return false;
            if(minCount > 0) minCount--;
            maxCount--;
        }else if(ch === '*') {
            if(minCount > 0) minCount--;
            maxCount++;
        }
    }

    return minCount === 0;
}
module.exports = {
    isValidString : isValidString
};

全部评论

相关推荐

如题,他是要劝退我了吗
椛鸣:根据你的时间 来给你安排任务 如果你时间长 可能会参与到一些长期的项目 时间短 那就只能做点零工
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务