您的位置:首页 > 编程语言 > Lua

[LeetCode]150 Evaluate Reverse Polish Notation

2015-01-09 15:15 453 查看
https://oj.leetcode.com/problems/evaluate-reverse-polish-notation/
http://blog.csdn.net/linhuanmars/article/details/21058857
public class Solution {
public int evalRPN(String[] tokens) {

// Assumptions...

Stack<Integer> stack = new Stack<>();
for (String s : tokens)
{
if (isop(s))
{
int vb = stack.pop();
int va = stack.pop();
stack.push(calc(va, vb, s));
}
else
{
stack.push(Integer.parseInt(s));
}
}

return stack.pop();
}

private boolean isop(String s)
{
return s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/");
}

private int calc(int a, int b, String op)
{
if (op.equals("+"))
return a + b;
else if (op.equals("-"))
return a - b;
else if (op.equals("*"))
return a * b;
else
return a / b;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode