[LeetCode] 150. Evaluate Reverse Polish Notation 计算逆波兰表达式

2021年09月15日 阅读数:1
这篇文章主要向大家介绍[LeetCode] 150. Evaluate Reverse Polish Notation 计算逆波兰表达式,主要内容包括基础应用、实用技巧、原理机制等方面,希望对大家有所帮助。

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

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

Note:python

  • 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:express

Input: ["2", "1", "+", "3", "*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9

Example 2:app

Input: ["4", "13", "5", "/", "+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6

Example 3:ide

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

逆波兰表达式,全部操做符置于操做数的后面,所以也被称为后缀表示法。逆波兰记法不须要括号来标识操做符的优先级。post

逆波兰记法中,操做符置于操做数的后面。例如表达“三加四”时,写做“3 4 +”,而不是“3 + 4”。若是有多个操做符,操做符置于第二个操做数的后面,因此常规中缀记法的“3 - 4 + 5”在逆波兰记法中写做“3 4 - 5 +”:先3减去4,再加上5。使用逆波兰记法的一个好处是不须要使用括号。例如中缀记法中“3 - 4 * 5”与“(3 - 4)*5”不相同,但后缀记法中前者写作“3 4 5 * -”,无歧义地表示“3 (4 5 *) -”;后者写作“3 4 - 5 *”。lua

逆波兰表达式的解释器通常是基于堆栈的。解释过程通常是:操做数入栈;遇到操做符时,操做数出栈,求值,将结果入栈;当一遍后,栈顶就是表达式的值。所以逆波兰表达式的求值使用堆栈结构很容易实现,而且能很快求值。url

注意:逆波兰记法并非简单的波兰表达式的反转。由于对于不知足交换律的操做符,它的操做数写法仍然是常规顺序,如,波兰记法“/ 6 3”的逆波兰记法是“6 3 /”而不是“3 6 /”;数字的数位写法也是常规顺序。code

解法1: 栈Stack

解法2: 递归

Java:

public class Solution {
    public int evalRPN(String[] tokens) {
        int a,b;
		Stack<Integer> S = new Stack<Integer>();
		for (String s : tokens) {
			if(s.equals("+")) {
				S.add(S.pop()+S.pop());
			}
			else if(s.equals("/")) {
				b = S.pop();
				a = S.pop();
				S.add(a / b);
			}
			else if(s.equals("*")) {
				S.add(S.pop() * S.pop());
			}
			else if(s.equals("-")) {
				b = S.pop();
				a = S.pop();
				S.add(a - b);
			}
			else {
				S.add(Integer.parseInt(s));
			}
		}	
		return S.pop();
	}
}

Java:

public int evalRPN(String[] a) {
  Stack<Integer> stack = new Stack<Integer>();
  
  for (int i = 0; i < a.length; i++) {
    switch (a[i]) {
      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.parseInt(a[i]));
    }
  }
  
  return stack.pop();
}

Python:  

# Time:  O(n)
# Space: O(n)
import operator

class Solution:
    # @param tokens, a list of string
    # @return an integer
    def evalRPN(self, tokens):
        numerals, operators = [], {"+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.div}
        for token in tokens:
            if token not in operators:
                numerals.append(int(token))
            else:
                y, x = numerals.pop(), numerals.pop()
                numerals.append(int(operators[token](x * 1.0, y)))
        return numerals.pop()

if __name__ == "__main__":
    print(Solution().evalRPN(["2", "1", "+", "3", "*"]))
    print(Solution().evalRPN(["4", "13", "5", "/", "+"]))
    print(Solution().evalRPN(["10","6","9","3","+","-11","*","/","*","17","+","5","+"]))

C++:

class Solution {
public:
    int evalRPN(vector<string> &tokens) {
        if (tokens.size() == 1) return atoi(tokens[0].c_str());
        stack<int> s;
        for (int i = 0; i < tokens.size(); ++i) {
            if (tokens[i] != "+" && tokens[i] != "-" && tokens[i] != "*" && tokens[i] != "/") 
       {
                s.push(atoi(tokens[i].c_str()));
            } else {
                int m = s.top();
                s.pop();
                int n = s.top();
                s.pop();
                if (tokens[i] == "+") s.push(n + m);
                if (tokens[i] == "-") s.push(n - m);
                if (tokens[i] == "*") s.push(n * m);
                if (tokens[i] == "/") s.push(n / m);
            }
        }
        return s.top();
    }
};

C++:  

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        int op = tokens.size() - 1;
        return helper(tokens, op);
    }
    int helper(vector<string>& tokens, int& op) {
        string s = tokens[op];
        if (s == "+" || s == "-" || s == "*" || s == "/") {
            int v2 = helper(tokens, --op);
            int v1 = helper(tokens, --op);
            if (s == "+") return v1 + v2;
            else if (s == "-") return v1 - v2;
            else if (s == "*") return v1 * v2;
            else return v1 / v2;
        } else {
            return stoi(s);
        }
    }
};

  

 

 

All LeetCode Questions List 题目汇总