My Accepted Answer in Java


  • 2
    I
    public class Solution {
    public int evalRPN(String[] tokens) {
        Stack<String> num = new Stack<String>();
        // Stack operator = new Stack();
        String result = "";
        
        if (tokens.length == 1) 
            return Integer.parseInt(tokens[0]);
        
        for (String str : tokens) {
            if (str.compareTo("+") != 0 && str.compareTo("-") !=0
                && str.compareTo("*") !=0 && str.compareTo("/") !=0) {
                    num.push(str);
            } else {
                String r = num.pop();
                String l = num.pop();
                result = calculation(l, r, str);
                num.push(result);
            }
        }
        result = num.pop();
        return Integer.parseInt(result);
    }
    
    public String calculation(String l, String r, String op) {
        StringBuffer resultStr = new StringBuffer();
        int left = Integer.parseInt(l);
        int right = Integer.parseInt(r);
        int result = 0;
        
        if(op.compareTo("+") == 0) {
            result = left + right;
        } else if(op.compareTo("-") == 0) {
            result = left - right;
        } else if(op.compareTo("*") == 0) {
            result = left * right;
        } else {
            result = left / right;
        }
        resultStr.append(result);
        return resultStr.toString();
    }
    

    }


  • 0
    S
    1. Great to use Stack!
    2. It is of no use to create a StringBuffer in calculation, just return resultStr + "" is enough
    3. In calculation, switch case is better? to select operator.

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.