leetcode经典例题第二题,关于栈的操作。
题目描述
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:
解题思路
这一题提示信息是用栈来实现,那么思路为:如果当前元素是数字就入栈,否则就是运算符,那么就将这个运算符前面两个数字进行相应操作,并且将这个操作结果重新再放入栈中,参与下一次的运算。
提交代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 import java.util.Stack;public class Solution { public int evalRPN (String[] tokens) { Stack<Integer> stack = new Stack<>(); int res = 0 ; if (tokens == null || tokens.length <= 0 ){ return res; } if (tokens.length == 1 ){ res = Integer.valueOf(tokens[0 ]); } for (String str:tokens){ if (str.equals("+" ) || str.equals("-" ) || str.equals("*" ) || str.equals("/" )){ int v1 = stack.pop(); int v2 = stack.pop(); if (str.equals("+" )){ res = v1+v2; }else if (str.equals("-" )){ res = v2-v1; }else if (str.equals("*" )){ res = v1*v2; }else if (str.equals("/" )){ res = v2/v1; } stack.push(res); }else { stack.push(Integer.valueOf(str)); } } return res; } }