知识点:栈
后缀表达式把运算符写在运算对象的后面,例如,把a+b写成ab+,所以也称为后缀式。这种表示法的优点是根据运算对象和算符的出现次序进行计算,不需要使用括号,也便于用械实现求值。对于表达式x:=(a+b)*(c+d),其后缀式为xab+cd+*:=。
若想对后缀表示式进行运算,需要使用到栈,若遍历到数字,则将其推入栈中,若遍历到表达式,则将栈中的两个数字推出,进行运算后将结果再推入栈,最终栈内的元素即为运算结果。
在遇到-和/两个运算符时,需要注意数字的运算顺序,第一个推出栈的数字要作为被减数或者被除数。
Java题解如下:
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param tokens string字符串一维数组
* @return int整型
*/
public int calculatePostfix (String[] tokens) {
// write code here
Deque<Integer> stack = new ArrayDeque<>();
for(String token: tokens) {
Integer res = 0;
if(token.equals("+")) {
res = stack.pop() + stack.pop();
}else if(token.equals("-")) {
int digit = stack.pop();
res = stack.pop() - digit;
}else if(token.equals("*")) {
res = stack.pop() * stack.pop();
}else if(token.equals("/")) {
int digit = stack.pop();
res = stack.pop() / digit;
}else {
res = Integer.parseInt(token);
}
stack.push(res);
}
return stack.peek();
}
}



京公网安备 11010502036488号