首页 > 代码库 > leetcode 150. Evaluate Reverse Polish Notation

leetcode 150. 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

主要是栈的应用:

tockens[i]如果是操作数,直接压栈。如果是运算符,则两次pop的结果运算后压栈。

最后栈中的元素即为结果。

 1 int evalRPN(vector<string> &tokens)  2     { 3         int op_a, op_b; 4         stack<int> sk; 5         for (int i = 0; i < tokens.size(); i++) 6         { 7             string str = tokens[i]; 8             if ((str[0] == +) || (str[0] == - && str.size() == 1) || (str[0] == *) || (str[0] == /)) 9             {10                 op_a = sk.top();11                 sk.pop();12                 op_b = sk.top();13                 sk.pop();14                 switch(str[0])15                 {16                     case +:17                         sk.push(op_b + op_a);18                         break;19                     case -:20                         sk.push(op_b - op_a);21                         break;22                     case *:23                         sk.push(op_b * op_a);24                         break;25                     default:26                         sk.push(op_b / op_a);27                 }28             }29             else 30             {31                 sk.push(atoi(str.c_str()));32             }33         }34         return sk.top();35     }

 

leetcode 150. Evaluate Reverse Polish Notation