DEV Community

Masaki Fukunishi
Masaki Fukunishi

Posted on

LeetCode #20 Valid Parentheses with JavaScript

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;
};
Enter fullscreen mode Exit fullscreen mode
  • Time complexity: O(n)
  • Space complexity: O(n)
  1. save the target parentheses in an object with keys and values
  2. add the string to the stack array in a for loop
  3. if the closing parenthesis is a pair with the last value in the stack array, remove it from the stack array
  4. return true if the stack array is finally empty, false if it remains

Top comments (0)