题目:
思考:
- 逆波兰表达式还是比较容易实现计算的
- 栈
实现:
class Solution {
public:
int evalRPN(vector<string>& tokens) {
int ref = 0;
stack<int> s;
for (auto t : tokens)
{
if (t == "+")
{
int right = s.top();
s.pop();
int left = s.top();
s.pop();
s.push(left + right);
}
else if (t == "-")
{
int right = s.top();
s.pop();
int left = s.top();
s.pop();
s.push(left - right);
}
else if (t == "*")
{
int right = s.top();
s.pop();
int left = s.top();
s.pop();
s.push(left * right);
}
else if (t == "/")
{
int right = s.top();
s.pop();
int left = s.top();
s.pop();
s.push(left / right);
}
else
{
s.push(stoi(t));
}
}
ref = s.top();
return ref;
}
};
改好看一点:
class Solution {
public:
int evalRPN(vector<string>& tokens) {
int ref = 0;
stack<int> s;
for (auto t : tokens)
{
int right =-1;
int left = -1;
int op=-1;
if (t=="+") op=0;
else if(t=="-") op=1;
else if (t=="*") op=2;
else if (t=="/") op=3;
if (op!=-1)
{
right = s.top();
s.pop();
left = s.top();
s.pop();
}
switch(op)
{
case 0:
s.push(left + right);
break;
case 1:
s.push(left - right);
break;
case 2:
s.push(left * right);
break;
case 3:
s.push(left / right);
break;
default:
s.push(stoi(t));
break;
}
}
ref = s.top();
return ref;
}
};