[LeetCode] 150. Evaluate Reverse Polish Notation Java
题目:
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
题意及分析:给出一个字符串,程序计算逆波兰式的结果,遍历表达式,碰到操作数入栈,碰到操作符就从栈顶取出两个操作数,再将计算后的结果入栈,最后栈中剩余的唯一操作数就是计算结果。 这里注意的是string类型判断值是否相等需要用.equals。
代码:
public class Solution { public int evalRPN(String[] tokens) { Stack<Integer> stack=new Stack<>(); for(int i=0;i<tokens.length;i++){ String token=tokens[i]; if(token.equals("+")||token.equals("-")||token.equals("*")||token.equals("/")){ int op1=stack.pop(); int op2=stack.pop(); if(token.equals("+")){ stack.push(op2+op1); } if(token.equals("-")){ stack.push(op2-op1); } if(token.equals("*")){ stack.push(op2*op1); } if(token.equals("/")){ stack.push(op2/op1); } }else{ stack.push(Integer.parseInt(token)); } } int res=stack.peek(); // System.out.println(res); return res; } }