Solution to LeetCode's 20. Valid Parentheses with JavaScript.
Solution
/** * @param {string} s * @return {boolean} */ const isValid = (s) => { const map = { "(": ")", "[": "]", "{": "}", }; const stack = []; for (let i = 0; i < s.length; i++) { if (stack.length > 0 && map[stack[stack.length - 1]] === s[i]) { stack.pop(); } else { stack.push(s[i]); } } return stack.length === 0; };
- Time complexity: O(n)
- Space complexity: O(n)
- save the target parentheses in an object with keys and values
- add the string to the stack array in a for loop
- if the closing parenthesis is a pair with the last value in the stack array, remove it from the stack array
- return true if the stack array is finally empty, false if it remains
Top comments (0)