逆波兰表达式是用栈存取数字和运算符
规则就是
遇到运算符就从栈弹出两个数字,运算后把结果再存进去,不断进行
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
import java.util.Stack; public class Solution { public int evalRPN(String[] tokens) { Stack<Integer> stack = new Stack(); for(int i = 0;i < tokens.length;i++) { String cur = tokens[i]; if(cur.length()>1||(cur.charAt(0)>='0'&&cur.charAt(0)<='9')) stack.push(Integer.parseInt(cur)); else { int a = stack.pop(); int b = stack.pop(); if(cur.equals("+")) stack.push(b+a); else if(cur.equals("*")) stack.push(b*a); else if(cur.equals("-")) stack.push(b-a); else if(cur.equals("/")) stack.push(b/a); } } return stack.pop(); } }