根据逆波兰表示法,求表达式的值。
有效的运算符包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。
说明:
整数除法只保留整数部分。
给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。
示例 1:
输入: ["2", "1", "+", "3", "*"]
输出: 9
解释: ((2 + 1) * 3) = 9
示例 2:
输入: ["4", "13", "5", "/", "+"]
输出: 6
解释: (4 + (13 / 5)) = 6
示例 3:
输入: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
输出: 22
解释:
((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
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/
从图中规律可以发现,给出的vector<string>实际上是二叉树的后序遍历。先计算的是1+2,然后是3*3,这给了我们做题的思路,在vector当中遍历,遇见符号的时候,因为是后序遍历,所以符号前的两个数字应该去执行数字所代表的运算。并将结果去覆盖符号。然后删除被操作的两个数字。
由于题中给的是vector所以它的pop将会非常的耗时,我们自然而然的想到stack的pop操作非常方便,那么可以在遍历vector的时候,将数字压进stack,当遇到符号的时候再取出来,然后执行字符所代表的操作,再将结果压入栈。
下面看代码
#include <iostream>
#include <vector>
#include <string>
#include <cctype>
#include <stack>
#include <cstdlib>
/* 后缀表达式 */
using namespace std;
class Solution
{
stack<int> tmp;
int a;
int b;
public:
int evalRPN(vector<string>& tokens)
{
for (auto & vsi:tokens)
{
/* 判断string的第一个字符是不是数字,有专门的函数isdigit,
当然第一个不是数字时也有可能是负数,但是负数一定有两个或者两个以上的
字符,那么就可以用长度去判断,如下*/
if (isdigit(vsi[0])||vsi.size()>1)
{
/* 将数字入栈 */
tmp.push(atoi(vsi.c_str()));
}
else
{
/* 当是符号的时候,取出栈顶的前两个元素,执行操作,并将结果存入 */
a = tmp.top();
tmp.pop();
b = tmp.top();
switch (vsi[0])
{
case '+':
tmp.top() = b + a;
break;
case '-':
tmp.top() = b - a;
break;
case '*':
tmp.top() = b * a;
break;
case '/':
tmp.top() = b / a;
break;
}
}
}
/* 返回结果 */
return tmp.top();
}
};
int main()
{
vector<string> vs{ "10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+" };
Solution test;
cout << test.evalRPN(vs);
system("pause");
return 0;
}