LeetCode-Evaluate Reverse Polish Notation

Description:
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

题意:计算一个逆波兰式的结果

解法:这道题可以利用栈来求解,遍历字符串,如果是数字则压入栈中,否则,在栈中弹出两个数,进行运算(+、-、*、/)后将结果压入栈中;当遍历完所有的字符串后,栈中的那个元素就是最后所要求解的结果;因为,这里保证了所给的逆波兰式是合法的,所以我们不需要去判断合法性;同时,需要注意的一点是,进行计算的时候,栈中弹出的两个数中首先弹出的是第二操作数,后弹出的是第一操作数;

Java
class Solution {
    public int evalRPN(String[] tokens) {
        LinkedList stack = new LinkedList<>();
        for (String s : tokens) {
            if (Character.isDigit(s.charAt(0)) || 
                (s.length() > 1 && Character.isDigit(s.charAt(1)))) {
                stack.push(s);
            } else {
                int num2 = Integer.parseInt(stack.pop());
                int num1 = Integer.parseInt(stack.pop());
                int result = 0;
                switch(s.charAt(0)) {
                    case '+':
                        result = num1 + num2;
                        break;
                    case '-':
                        result = num1 - num2;
                        break;
                    case '/':
                        result = num1 / num2;
                        break;
                    case '*':
                        result = num1 * num2;
                        break;
                    default:
                        break;
                }
                stack.push(String.valueOf(result));
            }
        }
        
        return Integer.parseInt(stack.pop());
    }
}

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