/**
* Index: 150
* Title: Evaluate Reverse Polish Notation
* Author: ltree98
**/
题意
计算逆波兰式(逆波兰式也可称作后缀表示法,它将操作符置于操作数后面,这种方式不需要用括号来标识操作符的优先级)的值,合法的操作符有 + - * / ,每个操作数为一个整数或表达式。
注意:
- 除法运算,需要向下取整
- 给定的表达式一定合法。即一定会有个最终值,不会有除0等不合法行为
我的
思路
用栈结构,进行计算;注意 - / 运算符时,弹出栈操作数的位置顺序。
时间复杂度:O(n)
空间复杂度:O(n)
实现
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> answer;
for(int i = 0; i < tokens.size(); i++) {
if(tokens[i][0] == '+') {
int param1 = answer.top();
answer.pop();
int param2 = answer.top();
answer.pop();
answer.push(param1 + param2);
}
else if(tokens[i][0] == '-' && tokens[i].length() == 1) {
int param1 = answer.top();
answer.pop();
int param2 = answer.top();
answer.pop();
answer.push(param2 - param1);
}
else if(tokens[i][0] == '*') {
int param1 = answer.top();
answer.pop();
int param2 = answer.top();
answer.pop();
answer.push(param1 * param2);
}
else if(tokens[i][0] == '/') {
int param1 = answer.top();
answer.pop();
int param2 = answer.top();
answer.pop();
answer.push(param2 / param1);
}
else {
int val = std::stoi(tokens[i]);
answer.push(val);
}
}
return answer.top();
}
};
进阶
思路
基本都是通过栈来做,非常标准的栈练习题;差别在于代码的简洁度不同。
比如用switch替换一堆if-elseif-else,或者用lambda。
实现
class Solution {
public:
int evalRPN(vector<string>& tokens) {
unordered_map<string, function<int (int, int) > > map = {
{ "+" , [] (int a, int b) { return a + b; } },
{ "-" , [] (int a, int b) { return a - b; } },
{ "*" , [] (int a, int b) { return a * b; } },
{ "/" , [] (int a, int b) { return a / b; } }
};
std::stack<int> stack;
for (string& s : tokens) {
if (!map.count(s)) {
stack.push(stoi(s));
} else {
int op1 = stack.top();
stack.pop();
int op2 = stack.top();
stack.pop();
stack.push(map[s](op2, op1));
}
}
return stack.top();
}
};