moonlightshadow123
6/19/2017 - 9:55 AM

20. Valid Parentheses

  1. Valid Parentheses
class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        stack = []
        operantDict = {'(':')', '[':']','{':'}'}
        for curChar in s:
            if curChar in operantDict.keys():
                stack.append(curChar)
            else:
                if len(stack) == 0:
                    return False
                prevChar = stack[-1]
                del stack[-1]
                if (prevChar not in operantDict.keys()) or (operantDict[prevChar] != curChar):
                    return False
        return len(stack) == 0

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

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.