Python method with explanation


  • 2
    H
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        dic={'(':')','[':']','{':'}'}
        stack=[]
        for ch in s:
            if ch in dic:
                stack.append(ch) #use a stack to store the left side of parenthesis.
            else:
                if len(stack)==0: 
                    return False   
                elif dic[stack.pop()]!=ch: #everytime meet a right side of the parenthesis, check if it matches to the stack
                    return False
        return not stack

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.