Scribbling

LeetCode: 150. Evaluate Reverse Polish Notation 본문

Computer Science/Coding Test

LeetCode: 150. Evaluate Reverse Polish Notation

focalpoint 2021. 11. 26. 11:36

stack을 사용

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        stack = []
        predefined_tokens = ['+', '-', '*', '/']
        operations = [lambda x, y : x + y, lambda x, y : x - y,
                     lambda x, y : x * y, lambda x, y : int(x / y)]
        for token in tokens:
            if token in predefined_tokens:
                num2 = stack.pop()
                num1 = stack.pop()
                idx = predefined_tokens.index(token)
                stack.append(operations[idx](num1, num2))
            else:
                stack.append(int(token))
        return stack[0]