LeetCode 150. 逆波兰表达式求值 Java
原题链接
中等
作者:
leo_0
,
2021-03-20 04:52:43
,
所有人可见
,
阅读 384
算法1
Java 代码
class Solution {
private final static Map<String, BiFunction<Integer, Integer, Integer>> map = new HashMap<>();
static{
map.put("+", (a,b)->a+b);
map.put("-", (a,b)->a-b);
map.put("*", (a,b)->a*b);
map.put("/", (a,b)->a/b);
}
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for(String s:tokens){
if(map.containsKey(s)){
int num2 = stack.pop();
int num1 = stack.pop();
BiFunction<Integer, Integer, Integer> operation = map.get(s);
int res = operation.apply(num1, num2);
stack.push(res);
}else{
stack.push(Integer.valueOf(s));
}
}
return stack.pop();
}
}