题解 | #合法的括号字符串#
合法的括号字符串
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 };