PU Valid Parentheses

Jan 01, 1970

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

Python Solution 1:

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        l = []
        d = {'(': 1, '{': 2, '[': 3, ')': -1, '}': -2, ']': -3}
        for val in s:
            if d[val] > 0:
                l.append(val)
            else:
                if not l: return False
                _val = l.pop()
                if d[val] + d[_val]: return False
        return not l

Python Solution 2:

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        d = {')': '(', ']': '[', '}': '{'}
        stack = []
        for c in s:
            if c not in d:
                stack.append(c)
            else:
                if not stack: return False
                _c = stack.pop()
                if _c != d[c]: return False
        return not stack

Summary:

  • nothing to say

LeetCode: 20. Valid Parentheses