import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param tokens string字符串一维数组
* @return int整型
*/
public int calculatePostfix (String[] tokens) {
// write code here
Stack<Integer> stack = new Stack<>();
for (String s : tokens) {
if (Character.isDigit(s.charAt(s.length() - 1))) stack.push(Integer.parseInt(s));
else {
int b = stack.pop();
int a = stack.pop();
switch (s) {
case "+" : stack.push(a + b); break;
case "-" : stack.push(a - b); break;
case "*" : stack.push(a * b); break;
case "/" : stack.push(a / b); break;
}
}
}
return stack.peek();
}
}
- 根据题意,可以利用“栈”这种数据结构来辅助计算
- 遇到数字就直接入栈,这里需要注意数字可能是负数
- 遇到非数字就出栈栈顶的两个元素,然后进行 +-*/ 计算
- 最后栈顶的元素即为所求答案