Leetcode: Valid Parentheses

Question

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.

Show Tags
Show Similar Problems

Solution

Code

class Solution(object):
    def isValid(self, s):
        """ :type s: str :rtype: bool """

        if s=='':
            return True

        s = list(s)

        stack = []
        for temp in s:
            if temp=='[' or temp=='{' or temp=='(':
                stack.append(temp)
            if temp==')':
                if stack!=[]:
                    last = stack[-1]  
                    stack = stack[0:-1]
                    if last=='(':
                        continue
                    else:
                        return False
                else:
                    return False
            if temp=='}':
                if stack!=[]:
                    last = stack[-1]  
                    stack = stack[0:-1]
                    if last=='{':
                        continue
                    else:
                        return False
                else:
                    return False
            if temp==']':
                if stack!=[]:
                    last = stack[-1]  
                    stack = stack[0:-1]
                    if last=='[':
                        continue
                    else:
                        return False
                else:
                    return False


        return len(stack)==0

Error Path

  1. stack = stack[1:] should be stack = stack[0:-1]
  2. forget to add the case that last!=’)’

你可能感兴趣的:(Leetcode: Valid Parentheses)