Evaluate Reverse Polish Notation - LeetCode
Can you solve this real interview question? Evaluate Reverse Polish Notation - You are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation [http://en.wikipedia.org/wiki/Reverse_Polish_notation]. Evaluate t
leetcode.com
문제
You are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation.
Evaluate the expression. Return an integer that represents the value of the expression.
Note that:
- The valid operators are '+', '-', '*', and '/'.
- Each operand may be an integer or another expression.
- The division between two integers always truncates toward zero.
- There will not be any division by zero.
- The input represents a valid arithmetic expression in a reverse polish notation.
- The answer and all the intermediate calculations can be represented in a 32-bit integer.
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
Constraints:
- 1 <= tokens.length <= 104
- tokens[i] is either an operator: "+", "-", "*", or "/", or an integer in the range [-200, 200].
역 폴란드 표기법 식을 계산해서 답을 반환하는 문제이다.
역 폴란드 표기법은 연산자를 연산 대상 뒤에 쓰는 표기법이다.
내 풀이
class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for (String token : tokens) {
if(token.equals("+") || token.equals("*") || token.equals("/") || token.equals("-")) {
stack.push(calculate(s, stack.pop(), stack.pop()));
} else {
stack.push(Integer.parseInt(s));
}
}
return stack.pop();
}
public int calculate(String token, int a, int b) {
if (token.equals("+")) return a + b;
else if (token.equals("-")) return b - a;
else if (token.equals("*")) return a * b;
else return b / a;
}
}
간단하게 스택을 사용해서 풀이했다.
연산자가 연산대상보다 뒤에 나오기 때문에 연산 대상을 저장하고 있다가 연산자를 만나면 그 때 스택에서 값을 꺼내 연산을 진행하는 흐름이다.
자세히 설명하면 배열을 순회하면서 값이 연산자가 아니라면 스택에 값을 정수로 변환해 push
해준다.
연산자를 만나면 스택에서 연산할 값을 pop
해 연산한 뒤 그 결과를 다시 스택에 push
해주는 방식이다.
- 시간복잡도 : O(n) - 입력된 배열의 크기만큼 순회한다
- 공간복잡도 : O(n) - 스택에 최대 배열 크기/2 만큼의 원소를 담을 수 있다.
스택을 사용하여 풀이하는게 역 폴란드 표기법을 평가하는 코드를 작성하는 대표적인 방법이다.
'알고리즘 > 자료구조' 카테고리의 다른 글
[LeetCode] 219. Contains Duplicate II - Java (0) | 2023.08.31 |
---|---|
[LeetCode] 1. Two Sum - Java (0) | 2023.08.31 |
[LeetCode] 155. Min Stack - Java (0) | 2023.08.29 |
[LeetCode] 21. Merge Two Sorted Lists - Java (0) | 2023.08.29 |
[LeetCode] 2. Add Two Numbers - Java (0) | 2023.08.29 |