Java 13 ms Solution w/ Stack


  • 0
    X
    public int evalRPN(String[] tokens) {
        Stack<Integer> opands = new Stack<Integer>();
        for(String token:tokens){
            char[] cc = token.toCharArray();
            if((cc[0]=='+' || cc[0]=='-' || cc[0]=='*' || cc[0]=='/') && cc.length==1){
                int op1 = opands.pop();
                int op2 = opands.pop();
                if(cc[0]=='+') opands.push(op2+op1);
                if(cc[0]=='-') opands.push(op2-op1);
                if(cc[0]=='*') opands.push(op2*op1);
                if(cc[0]=='/') opands.push(op2/op1);
            }else{
                opands.push(charArray2Int(cc));
            }
        }
        return opands.pop();
    }
    
    private int charArray2Int(char[] cc){
        int len =cc.length;
        int num =0;
        int i=0;
        int sign =1;
        if(cc[0]=='-') {
            sign = -1;
            i=1;
        }
        for(; i<len;i++){
            num = (cc[i]-'0') + num*10;
        }
        return sign*num;
    }

Log in to reply
 

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