150. Evaluate Reverse Polish Notation

变成符号在两个数前面,stack做


wyt211 发表于 2018-10-10 04:35
请问最后一题,可以把input reverse一下以后,按照lc的原题做法做嘛?

题有点不一样, 他是一个运算符后面可以跟多个数,数之间空格隔开, 运算符只有+, -
比如 * (+ 2 4 1) 3 =( 2 + 4 + 1 ) * 3. 1point3acres
我是用两个stack,一个存数字,一个存运算符



Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Note:
* Division between two integers should truncate toward zero.
* The given RPN expression is always valid. That means the expression would always evaluate to a result and there won't be any divide by zero operation.
Example 1:
Input: ["2", "1", "+", "3", "*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9
Example 2:
Input: ["4", "13", "5", "/", "+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6
Example 3:
Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
Output: 22
Explanation: 
  ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22



1. 
Integer.valueOf(String) returns an integer 

https://www.tutorialspoint.com/java/number_valueof.htm




2. 
Switch 

Case

Default 


https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html




class Solution {
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<>();
        for(String token : tokens){
            switch(token){
                case "+":
                    stack.push(stack.pop() + stack.pop());
                    break;
                case "-":
                    stack.push(-stack.pop() + stack.pop());
                    break;
                case "*":
                    stack.push(stack.pop() * stack.pop());
                    break;
                case "/":
                    int n1 = stack.pop(), n2 = stack.pop();
                    stack.push(n2 / n1);
                    break;
                default:
                    stack.push(Integer.valueOf(token));
            }
        }
        return stack.pop();
        
    }
}

 

posted on 2018-11-09 06:57  猪猪&#128055;  阅读(116)  评论(0)    收藏  举报

导航