Skip to content

20. Valid Parentheses

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

js
/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function(s) {
  var stack = []
  var labels = {
    '(': ')',
    '[': ']',
    '{': '}'
  }

  for (let ch of s) {
    if (labels.hasOwnProperty(ch)) {
      stack.push(ch)
    } else if (stack.length === 0 || labels[stack.pop()] !== ch) {
      return false
    }
  }

  return stack.length === 0
}
py
class Solution(object):

    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        stack, labels = [], {'(': ')', '[': ']', '{': '}'}
        for ch in s:
            if ch in labels:
                stack.append(ch)
            elif len(stack) == 0 or labels[stack.pop()] != ch:
                return False
        return len(stack) == 0