逆波兰表达式:
逆波兰表达式是一种后缀表达式,所谓后缀就是指算符写在后面。
平常使用的算式则是一种中缀表达式,如 ( 1 + 2 ) * ( 3 + 4 ) 。 该算式的逆波兰表达式写法为 ( ( 1 2 + ) ( 3 4 + ) * ) 。 逆波兰表达式主要有以下两个优点:
去掉括号后表达式无歧义,上式即便写成 1 2 + 3 4 + * 也可以依据次序计算出正确结果。 适合用栈操作运算:遇到数字则入栈;遇到算符则取出栈顶两个数字进行计算,并将结果压入栈中。
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/evaluate-reverse-polish-notation 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| class Solution { public: int evalRPN(vector<string>& tokens) { stack<int> s; for(auto& token : tokens) { if(token != "+" && token != "-" && token != "*" && token != "/") s.push(stoi(token)); else { int num2 = s.top(); s.pop(); int num1 = s.top(); s.pop(); switch(token[0]) { case '+': s.push(num1 + num2); break; case '-': s.push(num1 - num2); break; case '*': s.push(num1 * num2); break; case '/': s.push(num1 / num2); } } } return s.top(); } };
|