leetcode 144: Evaluate Reverse Polish Notation

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +, -, *, /. Each operand may be an integer or another expression.

Some examples:

  ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
  ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6


public class Solution {
    public int evalRPN(String[] tokens) {
        
        Stack<Integer> stack= new Stack<Integer>();
        for(int i=0; i<tokens.length; i++) {
            String s = tokens[i];
            
            if(s.length()>1) {
                int x = 0;
                int flag = 1;
                for(int j=0; j<s.length();  j++) {
                    if(s.charAt(j)=='-') flag =-1;
                    else x = 10*x + s.charAt(j) - '0';
                }
                stack.push(flag*x);
            } else {
                char c = s.charAt(0);
                if(c<'0'||c>'9') {
                    int y = stack.pop();
                    int x = stack.pop();
                    if(c=='+') stack.push(x+y);
                    else if(c=='-') stack.push(x-y);
                    else if(c=='*') stack.push(x*y);
                    else if(c=='/') stack.push(x/y);
                } else stack.push(c-'0');
            }
        }
        
        if(stack.isEmpty() ) return 0;
        else return stack.pop();
        
    }
}


你可能感兴趣的:(leetcode 144: Evaluate Reverse Polish Notation)