921.js
/** ------------------------------------------------------------------------------
*
* 921. Minimum Add to Make Parentheses Valid
* Topics: Stack, Greedy
* https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/?envType=daily-question&envId=2024-10-09
*
------------------------------------------------------------------------------ */
/**
* @param {string} s
* @return {number}
*/
var minAddToMakeValid = function (s) {
const stack = []
for (let c of s) {
if (c === "(") {
stack.push(c)
} else {
if (stack[stack.length - 1] === "(") {
stack.pop()
} else {
stack.push(c)
}
}
}
return stack.length
}
/**
* 천재
*/
var minAddToMakeValid = function (s) {
let left = 0,
right = 0
for (let c of s) {
if (c === "(") left++
else if (!left) right++
else left--
}
return left + right
}
console.log(minAddToMakeValid("())"))