DEV Community

Masaki Fukunishi
Masaki Fukunishi

Posted on

1

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)

πŸ‘‹ Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay