所有的LeetCode题解索引,可以看这篇文章——【算法和数据结构】LeetCode题解。
一、题目
二、解法
思路分析:我们常看见的表达式是中缀表达式(关于中缀表达式的定义可以参考前缀、中缀、后缀表达式),中缀表达式比较符合我们的习惯,但对于计算机来说不是特别友好:计算机需要从左到右扫描,然后还有比较优先级,做完部分运算后还可能要回退。那么将中缀表达式,转化为后缀表达式之后,就不一样了,计算机可以利用栈来顺序处理,不需要考虑优先级了。也不用回退了, 所以后缀表达式对计算机来说是非常友好的。程序当中用到的stoll函数,用来将字符串转成int类型。
程序如下:
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> st;
int num1 = 0, num2 = 0;
for (int i = 0; i < tokens.size(); ++i) {
if (tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "/" || tokens[i] == "*") {
num1 = st.top();
st.pop();
num2 = st.top();
st.pop();
if (tokens[i] == "+") st.push(num1 + num2);
else if (tokens[i] == "-") st.push(num2 - num1);
else if (tokens[i] == "/") st.push(ceil(num2 / num1));
else st.push(num1 * num2);
}
else {
st.push(stoll(tokens[i]));
}
}
return st.top();
}
};
复杂度分析:
- 时间复杂度: O ( n ) O(n) O(n)。
- 空间复杂度: O ( n ) O(n) O(n)。
三、完整代码
# include <iostream>
# include <stack>
# include <string>
# include <vector>
# include <cmath>
using namespace std;
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<long long> st;
long long num1 = 0, num2 = 0;
for (int i = 0; i < tokens.size(); ++i) {
if (tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "/" || tokens[i] == "*") {
num1 = st.top();
st.pop();
num2 = st.top();
st.pop();
if (tokens[i] == "+") st.push(num1 + num2);
else if (tokens[i] == "-") st.push(num2 - num1);
else if (tokens[i] == "/") st.push(ceil(num2 / num1));
else st.push(num1 * num2);
}
else {
st.push(stoll(tokens[i]));
}
}
return st.top();
}
};
int main()
{
Solution s1;
//vector<string> v = { "2", "1", "+", "3", "*" };
vector<string> v = { "10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+" };
//vector<string> v = { "4", "13", "5", "/", "+" };
int result = s1.evalRPN(v);
cout << "result = " << result <<endl;
system("pause");
return 0;
}
end