求逆波兰表达式的值。 在逆波兰表达法中,其有效的运算符号包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰计数表达。
输入: ["2", "1", "+", "3", "*"]
输出: 9
解释: ["2", "1", "+", "3", "*"] -> (2 + 1) * 3 -> 9
输入: ["4", "13", "5", "/", "+"]
输出: 6
解释: ["4", "13", "5", "/", "+"] -> 4 + 13 / 5 -> 6
逆波兰表达式是更利于计算机运算的表达式形式, 需要用到栈(先进后出的数据结构). 遍历表达式:
public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> s = new Stack<Integer>();
String operators = "+-*/";
for (String token : tokens) {
if (!operators.contains(token)) {
s.push(Integer.valueOf(token));
continue;
}
int a = s.pop();
int b = s.pop();
if (token.equals("+")) {
s.push(b + a);
} else if(token.equals("-")) {
s.push(b - a);
} else if(token.equals("*")) {
s.push(b * a);
} else {
s.push(b / a);
}
}
return s.pop();
}
}
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.