LeetCode[150] 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

分析:

使用栈,很简单。

代码:

public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<Integer>();
for (String s : tokens){
switch (s){
case "+":
stack.push(stack.pop() + stack.pop());
break;
case "-":
stack.push(-(stack.pop() - stack.pop()));
break;
case "*":
stack.push(stack.pop() * stack.pop());
break;
case "/":
int a = stack.pop();
int b = stack.pop();
stack.push(b / a);
break;
default:
stack.push(Integer.parseInt(s));
break;
}
}
return stack.pop();
}
}

欢迎关注公众号: FullStackPlan 获取更多干货

Copyright © 2016 - 2017 LBD All Rights Reserved.

访客数 : | 访问量 :