150. Evaluate Reverse Polish Notation
Posted yaoyudadudu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.
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
解题思路:
这个是操作符在后面的形式。
我们可以用栈来辅助进行计算:
当遇见数字字符串时,需要转换成int并进行压栈;
当遇见操作符字符串时,取出栈顶前两个元素,计算后将结果压栈
代码:
class Solution { public: int evalRPN(vector<string>& tokens) { stack<int> stk; int ret = 0; for(int i = 0; i < tokens.size(); i++){ if(tokens[i].size() == 1){ int isOp = isOperator(tokens[i]); if(isOp >= 0){ int a = stk.top(); stk.pop(); int b = stk.top(); stk.pop(); if(isOp == 0){ stk.push(a+b); }else if(isOp == 1){ stk.push(b-a); }else if(isOp == 2){ stk.push(b*a); }else if(isOp == 3){ stk.push(b / a); } continue; } } int num = stoi(tokens[i]); stk.push(num); } return stk.top(); } private: int isOperator(string s){ if(s == "+") return 0; if(s == "-") return 1; if(s == "*") return 2; if(s == "/") return 3; return -1; } };
以上是关于150. Evaluate Reverse Polish Notation的主要内容,如果未能解决你的问题,请参考以下文章
150. Evaluate Reverse Polish Notation
150. Evaluate Reverse Polish Notation
leetcode150 Evaluate Reverse Polish Notation
[leetcode-150-Evaluate Reverse Polish Notation]