Skip to main content

Leetcode - 20. Valid Parentheses

· One min read

https://leetcode.com/problems/valid-parentheses/

Solution 1

/**
* @param {string} s
* @return {boolean}
*/
var isValid = function (s) {
if (s.length % 2 !== 0) {
return false;
}

const stack = [];
const brackets = {
'(': ')',
'{': '}',
'[': ']',
};

for (let i = 0; i < s.length; i++) {
if (Object.keys(brackets).includes(s[i])) {
stack.push(s[i]);
} else {
if (brackets[stack[stack.length - 1]] === s[i]) {
stack.pop();
} else {
return false;
}
}
}
return stack.length === 0;
};

Runtime: 240 ms

Memory Usage: 51.4 MB