Skip to main content

20.js

/** ------------------------------------------------------------------------------
*
* 2023-04-10
* Valid Parentheses
* https://leetcode.com/problems/valid-parentheses/
*
------------------------------------------------------------------------------ */
/**
* @param {string} s
* @return {boolean}
*/
var isValid = function (str) {
if (str.length <= 1 || str.length % 2 !== 0) return false

const stack = []
for (const s of str) {
if (mapping[s]) {
stack.push(mapping[s])
} else {
const last = stack.pop()
if (last !== s) return false
}
}

return stack.length === 0
}

const mapping = {
"(": ")",
"{": "}",
"[": "]",
}