Leetcode - Evaluate Reverse Polish Notation

My code:

public class Solution {
    public int evalRPN(String[] tokens) {
        if (tokens == null || tokens.length == 0) {
            return -1;
        }
        
        Stack<Integer> st = new Stack<Integer>();
        for (int i = 0; i < tokens.length; i++) {
            String token = tokens[i];
            if (token.charAt(token.length() - 1) >= '0' && token.charAt(token.length() - 1) <= '9') {
                st.push(Integer.parseInt(token));
            }
            else {
                Integer right = st.pop();
                Integer left = st.pop();
                int result = 0;
                if (token.equals("+")) {
                    result = left + right;
                }
                else if (token.equals("-")) {
                    result = left - right;
                }
                else if (token.equals("*")) {
                    result = left * right;
                }
                else {
                    result = left / right;
                }
                st.push(result);
            }
        }
        return st.pop();
    }
}

一开始以为是复杂题目,后来仔细看了下,发现是简单题。

Anyway, Good luck, Richardo! — 09/16/2016

    原文作者:Richardo92
    原文地址: https://www.jianshu.com/p/caee81e3a523#comments
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞