1题目理解
输入:一个字符串数组。这个字符串数组表示算数运算的逆波兰表示法。一般算数表示方法是2+1,逆波兰表示是2 1 +。
输出:一个int值。
Example 1:
Input: [“2”, “1”, “+”, “3”, “*”]
Output: 9
Explanation: ((2 + 1) * 3) = 9
Example 2:
Input: [“4”, “13”, “5”, “/”, “+”]
Output: 6
Explanation: (4 + (13 / 5)) = 6
Example 3:
Input: [“10”, “6”, “9”, “3”, “+”, “-11”, “", “/”, "”, “17”, “+”, “5”, “+”]
Output: 22
Explanation:
((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22
2 思路
只有遇到算式符号的时候才开始计算。其余时候将数值存储到stack。需要注意减法、除法的运算。
class Solution {public int evalRPN(String[] tokens) {Stack<Integer> stack = new Stack<Integer>();for(String token : tokens){if(token.equals("+")){Integer val = stack.pop()+stack.pop();stack.push(val);}else if(token.equals("-")){Integer o1 = stack.pop();Integer o2 = stack.pop();stack.push(o2-o1);}else if(token.equals("*")){stack.push(stack.pop() * stack.pop());}else if(token.equals("/")){Integer o1 = stack.pop();Integer o2 = stack.pop();stack.push(o2/o1);}else{stack.push(Integer.parseInt(token));}}return stack.pop();}
}