計算逆波蘭表達式表示的值 Evaluate Reverse Polish Notation

問題:express

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

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

Some examples:code

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

解決:token

① 使用棧,遇到操做符時出棧,而後將結果相加便可。ip

class Solution { //14ms
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<>();
        for (int i = 0;i < tokens.length ;i ++ ) {
            if(! ("+".equals(tokens[i])) && ! ("-".equals(tokens[i])) &&
                    ! ("*".equals(tokens[i])) && ! ("/".equals(tokens[i]))) {
                stack.push(Integer.parseInt(tokens[i]));
            }else{//遇到了操做符
                if("+".equals(tokens[i])){
                    int y = stack.pop();
                    int x = stack.pop();
                    int tmp = x + y;
                    stack.push(tmp);
                }
                if("-".equals(tokens[i])){
                    int y = stack.pop();
                    int x = stack.pop();
                    int tmp = x - y;
                    stack.push(tmp);
                }
                if("*".equals(tokens[i])){
                    int y = stack.pop();
                    int x = stack.pop();
                    int tmp = x * y;
                    stack.push(tmp);
                }
                if("/".equals(tokens[i])){
                    int y = stack.pop();
                    int x = stack.pop();
                    int tmp = x / y;
                    stack.push(tmp);
                }
            }
        }
        return stack.pop();
    }
}
② 使用數組實現棧操做。get

class Solution { //5ms
    int index = 0;
    public int evalRPN(String[] tokens) {
        index = tokens.length - 1;
        return operate(tokens);
    }
    private int operate(String[] tokens){
        String s = tokens[index --];
        if(s.equals("+")||s.equals("*")||s.equals("-")||s.equals("/")){
            int y = operate(tokens);
            int x = operate(tokens);
            switch(s){
                case "+":
                    return (x + y);
                case "-":
                    return x - y;
                case "*":
                    return x * y;
                case "/":
                    return x / y;
            }
        }
        else
            return Integer.parseInt(s);it

        return -1;
    }
}io

相關文章
相關標籤/搜索