双端队列实现,坑很多
class Solution {
public:
int calculate(string s) {
deque<int> nums;
deque<char> ops;
for(int i = 0; i < s.length(); i++){
if(s[i] == ' ')
continue;
if(s[i] >= '0' && s[i] <= '9'){
int num = parseInt(s,i);
nums.push_back(num);
}
else if(s[i] == '+' || s[i] == '-'){
ops.push_back(s[i]);
}
else{
if(s[i] == '*'){
i++;
while(s[i] == ' ')
i++;
int right = parseInt(s,i);
int res = nums.back() * right;
nums.pop_back();
nums.push_back(res);
}
if(s[i] == '/'){
i++;
while(s[i] == ' ')
i++;
int right = parseInt(s,i);
int res = nums.back() / right;
nums.pop_back();
nums.push_back(res);
}
}
}
while(!ops.empty()){
if(ops.front() == '+'){
ops.pop_front();
int left = nums.front();
nums.pop_front();
int right = nums.front();
nums.pop_front();
int res = left + right;
nums.push_front(res);
}
else if(ops.front() == '-'){//这里不写else会报错
ops.pop_front();
int left = nums.front();
nums.pop_front();
int right = nums.front();
nums.pop_front();
int res = left - right;
nums.push_front(res);
}
}
return nums.back();
}
int parseInt(string &s, int &i){
int num = 0;
while(s[i] >= '0' && s[i] <= '9'){
num *= 10;
num += s[i] - '0';
i++;
}
i--;
return num;
}
};