leetcode 的一道利用栈来求后缀表达式的简单的栈应用的题
具体思路: 逐个字符串进行判断
1:如果是操作符则栈中至少有两个数,将两个数从栈中弹出,判断操作符是什么并对这两个数进行计算,再将计算的结果存到栈中。
2:如果是数字,则利用toInteger(const string &str)函数进行转化,然后压入栈中。
当vector遍历一遍之后,栈中就只剩下最终结果。
代码如下:
class Solution {
public:
int toInteger(const string &str){
int temp=1;
int result=0;
for(int i=str.length()-1;i>=1;i--){
int t=str[i]-'0';
result+=t*temp;
temp*=10;
}
if(str[0]!='-')
result+=(int)(str[0]-'0')*temp;
else result*=-1;
return result;
}
bool isOperator(const string &str){
if(str=="+"||str=="-"||str=="*"||str=="/")
return true;
else return false;
}
int evalRPN(vector<string> &tokens) {
stack<int> sta;
for(int i=0;i<tokens.size();i++){
if(isOperator(tokens[i])){
int a1=sta.top();sta.pop();
int a2=sta.top();sta.pop();
if(tokens[i]=="+") {
sta.push(a1+a2);
}
else if(tokens[i]=="-"){
sta.push(a2-a1);
}
else if(tokens[i]=="*"){
sta.push(a2*a1);
}
else if(tokens[i]=="/")
{
sta.push(a2/a1);
}
}
else{
sta.push(toInteger(tokens[i]));
}
}
return sta.top();
}
};