Share my AC python solution. small if check.


  • 0
    L

    I found some guys use a lot of if and switch to check the logic.
    Use some function, and the code will be easier to understand.

    class Solution:
    # @return a boolean
    def isValid(self, s):
        def isLeft(c):
            return c =='(' or c=='{' or c=='[';
        def isRight(c):
            return c==')' or c=='}' or c==']';
        def findRightLeft(c):
            if(c==')'): return '(';
            if(c=='}'): return '{';
            if(c==']'): return '[';
            
        stack=[];
        for c in s:
            if(isLeft(c)):
                stack.append(c);
            elif(isRight(c)):
                if(len(stack)==0):return False;
                elif(stack[-1] !=findRightLeft(c)):
                    return False;
                else:
                    stack.pop();
        return len(stack)==0;

  • 1
    G

    Here is mine. I tried to use less code to make it more readable and pythonic.

    class Solution:
        # @return a boolean
        def isValid(self, s):
            stack = collections.deque()
            pairs = {
                ')': '(',
                '}': '{',
                ']': '['}
            for c in s:
                if c in pairs.values():
                    stack.append(c)
                else:
                    if not stack or stack.pop() != pairs[c]:
                        return False
            return not stack

  • 0
    L

    nice solution.


Log in to reply
 

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