150逆波兰表达式求值(栈)

1、题目描述

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

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

说明:

整数除法只保留整数部分。
给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。

2、示例

输入: ["2", "1", "+", "3", "*"]
输出: 9
解释: ((2 + 1) * 3) = 9

3、题解

基本思想:栈

#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<stack>
using namespace std;
class Solution {
public:
	int evalRPN(vector<string>& tokens) {
		//基本思想:栈
		stack<int> st;
		int a, b, ans;
		for (auto& s : tokens)
		{
			if (s == "+" || s == "-" || s == "*" || s == "/")
			{
				b = st.top();
				st.pop();
				a = st.top();
				st.pop();
				switch (s[0])
				{
				case '+':
					ans = a + b;
					break;
				case '-':
					ans = a - b;
					break;
				case '*':
					ans = a * b;
					break;
				case '/':
					ans = a / b;
					break;
				default:
					break;
				}
				st.push(ans);
			}
			else
			{
				st.push(stoi(s));
			}
		}
		if (!st.empty())
			return st.top();
		else
			return 0;
	}
};
int main()
{
	Solution solute;
	vector<string> tokens = { "2", "1", "+", "3", "*" };
	cout << solute.evalRPN(tokens) << endl;
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章