소피it블로그

[LeetCode] 150번 Evaluate Reverse Polish Notation 문제 풀이 (파이썬) 본문

CS/알고리즘 문제풀이

[LeetCode] 150번 Evaluate Reverse Polish Notation 문제 풀이 (파이썬)

sophie_l 2022. 9. 22. 10:41

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

 

Evaluate Reverse Polish Notation - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

스택에 관한 기본적인 문제로, 크게 어렵지는 않았으나 음수를 고려 못하고 .isnumeric()을 써댄 탓에 꽤 헤맸다. 다른 답안 찾아다 놓고 일일이 한줄씩 고쳐가면서 간신히 오류를 파악함.

또한, 흥미롭게도 stack.append(token)과 stack += [token] 두 가지를 놓고 비교했을 때, 후자가 100ms정도 더 빨랐다. 이게 유의미한 영향이 있는 것인지는 모르겠지만..

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        operators = ["+", "-", "*", "/"]
        stack = []
        for token in tokens:
            if token not in operators:
            # if token.isnumeric(): # -11때문에 안됨! "-" 기호 때문에 numeric으로 인식 안함
                # stack.append(token) # 100ms정도 더 느림
                stack += [token]
            else:
                latter = stack.pop()
                former = stack.pop()
                stack.append(str(int(eval(former + token + latter))))
        return stack[0]