Yet Another Java Stack Solution


  • 0
    G

    Probably not the most elegant, but it scored better than ~87%

    public class Solution {
        private Stack<Integer> s;
        
        /**
         * Returns whether the given string is a number.
         * Can return true for numbers prepended with a sign "-"
         * Will return false for numbers containing decimals.
         * 
         * @param t
         * @return 
         */
        private boolean isNumber(String t) {
            char[] cees = t.toCharArray();
            if (('-' == cees[0]) && (cees.length > 1)) {
                for (int i = 1; i < cees.length; i++) {
                    if (!Character.isDigit(cees[i])) return false;
                }
            }
            else {
                for (char c: cees) {
                    if (!Character.isDigit(c)) return false;
                }
            }
            return true;
        }
        
        private void stackAdd() {
            int b = s.pop();
            int a = s.pop();
            s.push(a + b);
        }
        
        private void stackSubtract() {
            int b = s.pop();
            int a = s.pop();
            s.push(a - b);
        }
        
        private void stackMultiply() {
            int b = s.pop();
            int a = s.pop();
            s.push(a * b);
        }
        
        private void stackDivide() {
            int b = s.pop();
            int a = s.pop();
            s.push(a / b);
        }
        
        public int evalRPN(String[] tokens) {
            s = new Stack<>();
            for (String t: tokens) {
                if (isNumber(t)) s.push(Integer.parseInt(t));
                else if ("+".equals(t)) stackAdd();
                else if ("-".equals(t)) stackSubtract();
                else if ("*".equals(t)) stackMultiply();
                else if ("/".equals(t)) stackDivide();
            }
            return s.pop();
        }
    }
    

Log in to reply
 

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