Using stack - python O(n)


  • 0
    S
    class Solution(object):
        def calPoints(self, ops):
            """
            :type ops: List[str]
            :rtype: int
            """
            stack = []
            for op in ops:
                if op == "C":
                    stack.pop()
                elif op == "D":
                    if stack:
                        stack += 2*stack[-1],
                elif op == "+":
                    if len(stack) >= 2:
                        stack += (stack[-1] + stack[-2]),
                else:
                    stack += int(op),
                    
            ans = 0
            while stack:
                ans += stack.pop()
            
            return ans
    

Log in to reply
 

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