Tuesday, September 9, 2014

Leetcode: Valid Parentheses @Python

class Solution:
    # @return a boolean
    def isValid(self, s):
        n=len(s)
        stack=[]
        for i in range(n):
            if not stack:
                if s[i] in ['(','{','[']:
                    stack.append(s[i])
                else:
                    return False
            else:
                if (stack[-1]=='(' and s[i]==')') or (stack[-1]=="[" and s[i]=="]") or (stack[-1]=='{' and s[i]=='}'):
                    stack.pop()
                else:
                    stack.append(s[i])
        return not stack

No comments :

Post a Comment