[LeetCode] Evaluate Reverse Polish Notation
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
看到这道题说实话很有亲切感啊哈哈。因为以前上课的时候有次作业就和这道题灰常灰常的像,当时才开始学不久,把我折腾的哈哈~
刚开始我是按照以前的思考方式(因为懒)各种if statement啊各种special case啊。。写了一堆看着又恼火又长,然后还老不过。(抓狂的节奏-。-)
后来索性打乱开始重新写,事实证明还是要勤于思考。
果断直接用switch就轻松解决了。哈哈哈~~
再废话一句,后面参考了有人post的答案做了进一步修改,在“-”的运算时,固有思维是要有一个临时int来辅助计算,但是其实我们可以把“-”转换成“+”。
比如b-a=-a+b 这样我们就完全不需要临时的int了,不过除法还是需要的哈。
public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<Integer>();
for (int i = 0; i < tokens.length; i++) {
switch (tokens[i]) {
case "+":
stack.push(stack.pop() + stack.pop());
break;
case "-":
stack.push(-stack.pop() + stack.pop());
break;
case "/":
int a = stack.pop(), b = stack.pop();
stack.push(b/a);
break;
case "*":
stack.push(stack.pop() * stack.pop());
break;
default:
stack.push(Integer.parseInt(tokens[i]));
}
}
return stack.pop();
}
}
浙公网安备 33010602011771号