Solution
/**
* @param {string} s
* @return {boolean}
*/
var isValid = function(s) {
let stack = []
const map = {
'(': ')',
'[': ']',
'{': '}',
}
for (const c of s) {
if (['(', '[', '{'].includes(c)) {
stack.push(c)
} else if (c !== map[stack.pop()]) {
return false
}
}
return !stack.length
};
Complexity
- Time Complexity: O(N), where N is the size of
s
. - Space Complexity: O(N), where N is the size of
stack
, up to the size ofs
.