题目:
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +
, -
, *
, /
. Each operand may be an integer or another expression.
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
分析:
class Solution {
public int evalRPN(String[] tokens) {
//实现后缀表达式
//思路:使用stack存储数字,当遇到运算符时,就从stack中取出数字,之后把结果放回stack
if(tokens.length==0) return 0;
Stack<Integer> stack=new Stack<Integer>();
int firstNum=0,secNum=0;
for(int i=0;i<tokens.length;i++){
if(tokens[i].equals("+")){
firstNum=stack.pop();
secNum=stack.pop();
stack.push(firstNum+secNum);
}else if(tokens[i].equals("-")){
firstNum=stack.pop();
secNum=stack.pop();
stack.push(secNum-firstNum);
}else if(tokens[i].equals("*")){
firstNum=stack.pop();
secNum=stack.pop();
stack.push(firstNum*secNum);
}else if(tokens[i].equals("/")){
firstNum=stack.pop();
secNum=stack.pop();
stack.push(secNum/firstNum);
}else{
//只是数字,直接入栈
stack.push(Integer.parseInt(tokens[i]));
}
}
return stack.pop();
}
}