Java Solution using Stack


  • 0
    C
    public int evalRPN(String[] a) {
            if( a.length == 0 || a == null) return 0;
            Stack<Integer> stack = new Stack<>();
            Set<String> set = new HashSet<>(Arrays.asList("+", "-", "*", "/"));
            for(int i = 0; i < a.length; i ++) {
                if(!set.contains(a[i])) stack.push(Integer.parseInt(a[i]));
                else {
                    int tempRes = 0;
                    int late = stack.pop();
                    int former = stack.pop();
                    switch(a[i]) {
                        
                        case "+": tempRes = late + former;
                                  break;
                        case "-": tempRes = former - late;
                                  break;
                        case "*": tempRes = late * former;
                                  break;
                        case "/": tempRes = former / late;
                                  break;
                    }
                    stack.push(tempRes);
                }
            }
            return stack.pop();
        }

Log in to reply
 

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