LeetCode 150.逆波兰表达式求值
程序员文章站
2022-04-04 09:52:24
...
思路:
本题主要考察的是栈的知识点,看到逆波兰表达式就联想到栈的特点:
后进先出,与本题的运算符后置很相似
代码:
import java.util.Stack;
public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for (String s : tokens) {
switch (s) {
case "+" :
stack.push(stack.pop() + stack.pop());
break;
case "-" :
stack.push(-stack.pop() + stack.pop());
break;
case "*" :
stack.push(stack.pop() * stack.pop());
break;
case "/" :
int second = stack.pop();
int first = stack.pop();
stack.push(first / second);
break;
default:
stack.push(Integer.parseInt(s));
break;
}
}
return stack.pop();
}
}