Evaluate Reverse Polish Notation
문제 설명
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, and /. Each operand may be an integer or another expression.
Note that division between two integers should truncate toward zero.
It is guaranteed that the given RPN expression is always valid. That means the expression would always evaluate to a result, and there will not be any division by zero operation.
* 역폴란드 표기법 : https://ko.wikipedia.org/wiki/역폴란드_표기법
제한 사항
- 1 <= tokens.length <= 104
- tokens[i] is either an operator: "+", "-", "*", or "/", or an integer in the range [-200, 200].
입출력 예
Example 1:
Input: tokens = ["2","1","+","3","*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9
Example 2:
Input: tokens = ["4","13","5","/","+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6
Example 3:
Input: tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
Output: 22
Explanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22
Python 코드
Python code
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
for t in tokens:
if t not in {"+", "-", "*", "/"}:
stack.append(int(t))
else:
b, a = stack.pop(), stack.pop()
if t == "+": stack.append(a + b)
elif t == "-": stack.append(a - b)
elif t == "*": stack.append(a * b)
else: stack.append(trunc(a / b))
return stack[0]
* 참고 링크 : https://dev.to/seanpgallivan/solution-evaluate-reverse-polish-notation-192l
* 설명 참고 링크 : https://www.youtube.com/watch?v=P8xYysvjLd0
C++ 코드
C ++ code
int evalRPN(vector<string>& tokens)
{
stack<int>st;
for(auto it : tokens)
{
if(it=="+" || it=="-" || it=="*" || it=="/" )
{
int f = st.top();st.pop();
int s = st.top();st.pop();
if (it == "+")
{ int r = s + f; st.push(r); }
else if (it == "*")
{ int r = s * f; st.push(r); }
else if (it == "-")
{ int r = s - f; st.push(r); }
else if (it == "/")
{ int r = s / f; st.push(r); }
}
else{ st.push( stoi(it)); }
}
return st.top();
}
출처
https://leetcode.com/problems/evaluate-reverse-polish-notation/
'코딩테스트 > Leet Code' 카테고리의 다른 글
[Leet Code] 232. Implement Queue using Stacks (0) | 2022.01.21 |
---|---|
[Leet Code] 225. Implement Stack using Queues (0) | 2022.01.21 |
[Leet Code] 43. Multiply Strings (0) | 2022.01.14 |
[Leet Code] 27. Remove Element (0) | 2022.01.14 |
[Leet Code] 20. Valid Parentheses (0) | 2022.01.14 |