Java Solution using Stack


  • 0
    J
    public class Solution {
        public int evalRPN(String[] tokens) {
            
            int i=0;
            Stack<String> numStack = new Stack<String>();
            
            while(i<tokens.length)
            {
                if(isOp(tokens[i]))
                {
                    int val=doOperation(tokens[i],numStack.pop(),numStack.pop());
                    numStack.push(String.valueOf(val));
                    i++;
                    continue;
                }
                numStack.push(tokens[i]);
                i++;
            }
            
           return Integer.valueOf(numStack.pop());
        }
        
        public boolean isOp(String c){
            
            if(c.equals("*") ||c.equals("+") ||c.equals("-") ||c.equals("/") ) return true;
            
            return false;
        }
        
        public int doOperation(String op,String a,String b){
            
            int num1=Integer.valueOf(a);
            int num2=Integer.valueOf(b);
            
            if(op.equals("/")) return num2/num1;
            
            if(op.equals("*")) return num2*num1;
            
            if(op.equals("+")) return num2+num1;
            else return num2-num1;
            
        }
    }
    

Log in to reply
 

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