[LeetCode]150 Evaluate Reverse Polish Notation

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)