Algorithm

[Leetcode]150. Evaluate Reverse Polish Notation

rudgh99_algo 2024. 8. 1. 21:52

1. problem : 

https://leetcode.com/problems/evaluate-reverse-polish-notation/

 

2. solution 1 :

from typing import List

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        stack = []
        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 operations:
                temp1 = stack.pop()
                temp2 = stack.pop()
                operation = operations[token]
                result = operation(temp2, temp1)
                stack.append(result)
            else:
                stack.append(int(token))
        
        return stack[0]