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;
}

 

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