Share my solution


  • 0
    G
    def calculate(self, s):
        """
        :type s: str
        :rtype: int
        """
        from operator import add, sub, mul, div
        
        # format string to split digit and op with space
        strs = s.replace(' ', '') 
        strs = re.sub(r'([-+*/])',r' \1 ', strs)
        strs = strs.split()
        strs.append('=')
        
        # give op and define priority to calculate
        # then init oprand stack and op stack
        operator = {'+': add, '-': sub, '*':mul, '/':div, '=': None }
        priority = {'+': 1, '-': 1, '*':2, '/': 2, '=': 0}
        oprands, op = [1], ['*']
        
        for s in strs:
            if s not in operator.keys():
                oprands.append(int(s))
            elif priority[op[-1]] < priority[s]:
                op.append(s)
            else:
                # the priority of the op stack top >= the priority of the op s
                # calculate 
                while len(op)> 0 and priority[op[-1]] >= priority[s]:
                    a = oprands.pop()
                    b = oprands.pop()
                    o = op.pop()
                    oprands.append(operator[o](b,a))
                op.append(s)
                
        return oprands[0]

Log in to reply
 

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