首页 > 代码库 > LeetCode150 Evaluate Reverse Polish Notation

LeetCode150 Evaluate Reverse Polish Notation

Evaluate the value of an arithmetic expression in Reverse Polish Notation.  (Medium)

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

 

分析:

根据逆波兰表达式定义,建立栈存数字

遍历字符串,遇到数字,入栈,遇到运算符,取出栈顶两元素执行相应计算后将结果入栈

 

代码:

 1 class Solution {
 2 public:
 3     int evalRPN(vector<string>& tokens) {
 4         stack<int> s;
 5         for (int i = 0;i < tokens.size();i++) {
 6             if (tokens[i] == "+" || tokens[i] == "-" || tokens[i]== "*" || tokens[i] == "/") {
 7                 int num1 = s.top();
 8                 s.pop();
 9                 int num2 = s.top();
10                 s.pop();
11                 if (tokens[i] == "+") {
12                     int num = num1 + num2;
13                     s.push(num);
14                 }
15                 if (tokens[i] == "-") {
16                     int num = num2 - num1;
17                     s.push(num);
18                 }
19                 if (tokens[i] == "*") {
20                     int num = num2 * num1;
21                     s.push(num);
22                 }
23                 if (tokens[i] == "/") {
24                     int num = num2 / num1;
25                     s.push(num);
26                 }
27             }
28             else {
29                 s.push(atoi(tokens[i].c_str()));
30             }
31         }
32         int ans = s.top();
33         return ans;
34     }
35 };

 

LeetCode150 Evaluate Reverse Polish Notation