LeetCode刷题笔录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

这题原来写计算器的时候写过。有一个stack,对于input的string检查是什么类型的:如果是数字的话就丢到stack里;如果是算符的话就从stack里pop两个数字出来进行相应的计算,再把结果push回stack里。最后返回stack顶的元素就行了。

public class Solution {
    public int evalRPN(String[] tokens) {
        Stack<Integer> nums = new Stack<Integer>();
        
        for(String token : tokens){
            if(token.length() > 1 || (token.charAt(0) <= '9' && token.charAt(0) >= '0')){
                nums.push(Integer.parseInt(token));
            }
            else{
                int num1 = nums.pop();
                int num2 = nums.pop(); 
                switch (token.charAt(0)){
                    case '+':
                        nums.push(num1 + num2);
                        break;
                    case '-':
                        nums.push(num2 - num1);
                        break;
                    case '*':
                        nums.push(num2 * num1);
                        break;
                    case '/':
                        nums.push(num2 / num1);
                        break;
                }
            }
        }
        return nums.peek();
    }
}



你可能感兴趣的:(LeetCode,stack)