LeetCode 逆波兰表达式求值

根据逆波兰表示法,求表达式的值。

有效的运算符包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。

说明:

整数除法只保留整数部分。
给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 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

思路分析:分析几个表达式的展开会发现,

我们扫描给定的输入,
	如果是数字直接跳过,
	如果是运算符,则将在它之前最近的两个数字进行运算,然后继续扫描,重复此过程。

由于栈的后进先出的特性,所以我们采取栈作为辅助。上述分析转换为,如果是数字,则将它入栈,如果是运算符,将栈中pop出两个数字进行运算,运算的结果放回栈中,继续扫描。

class Solution {
public:
	int evalRPN(vector<string>& tokens){
		int tokensSize = tokens.size();
		stack<int> numStack;
		for (int index = 0; index < tokensSize; ++index) {
			//遇到运算符,从栈中取出两个数,进行运算
			if (tokens[index] == "+" || tokens[index] == "-" || tokens[index] == "*" || tokens[index] == "/") {
				char operation = tokens[index][0];//将字符串转换为字符
				//此处注意,由于栈的先进后出特性,第一个去出的是操作数,第二个取出的是被操作数
				int numTwo = numStack.top();//从栈中获取操作数
				numStack.pop();
				int numOne = numStack.top();//从栈中获取操作数
				numStack.pop();
				int tempRes = 0;
				switch (operation)
				{
				case '-': tempRes = numOne - numTwo; break;
				case '+': tempRes = numOne + numTwo; break;
				case '*': tempRes = numOne * numTwo; break;
				case '/': tempRes = numOne / numTwo; break;
				default:break;
				}
				numStack.push(tempRes);//计算结果后放回栈中
			}
			else {//操作数,将字符串转换为int放入栈中
				int number = stoi(tokens[index]);
				numStack.push(number);//放回栈中
			}
		}
		return numStack.top();
	}
};

在这里插入图片描述
这题感觉有点水,刚开始我还以为是表达式求值的那种需要考虑运算符的优先级。。。

猜你喜欢

转载自blog.csdn.net/qq_41855420/article/details/87903788