python solution using stack


  • 0
    P
    class Solution(object):
        def calPoints(self, ops):
            """
            :type ops: List[str]
            :rtype: int
            """
            stack = []
            size  = 0
            total_sum = 0
            for op in ops:
                if op == '+':
                    if size > 0:
                        last = stack.pop()
                        size -= 1
                        if size > 0:
                            second_last = stack.pop()
                            size -= 1
                            stack.append(second_last)
                            stack.append(last)
                            stack.append(last+second_last)
                            size += 3   
                            total_sum += stack[-1]
                elif op == 'C':
                    if size > 0:
                        add_this = stack.pop()
                        size -= 1
                        total_sum -= add_this 
                elif op == 'D':
                    if size > 0:
                        add_this = stack[-1]*2
                        stack.append(add_this)
                        size += 1
                        total_sum += add_this 
                else:
                    stack.append(int(op))
                    total_sum += int(op)
                    size += 1
                # print(stack, last_valid_index)
            return total_sum
    

Log in to reply
 

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