image_2022-04-26_17-22-43.png
60.4 KB
#medium
#N150. Evaluate Reverse Polish Notation
problem link
#solution
#N150. Evaluate Reverse Polish Notation
problem link
#solution
class Solution {
public int evalRPN(String[] tokens) {
Stack<String> stack = new Stack<>();
for(String t: tokens){
if(!stack.isEmpty() && t.charAt(0)<48 && t.length()==1){
int num2=Integer.parseInt(stack.pop());
int num1=Integer.parseInt(stack.pop());
stack.push(String.valueOf(calculate(num1, num2, t.charAt(0))));
}else{
stack.push(t);
}
}
return Integer.parseInt(stack.peek());
}
public int calculate(int num1, int num2, char ch){
switch(ch){
case '+': return num1+num2;
case '-': return num1-num2;
case '*': return num1*num2;
case '/': return num1/num2;
}
return 0;
}
}