题目来源:https://leetcode-cn.com/problems/basic-calculator-ii/
题目描述
给你一个字符串表达式 s ,请你实现一个基本计算器来计算并返回它的值。
整数除法仅保留整数部分。
示例 1:
输入:s = "3+22"
输出:7
示例 2:
输入:s = " 3/2 "
输出:1
示例 3:
输入:s = " 3+5 / 2 "
输出:5
提示:
1 <= s.length <= 3 * 105
s 由整数和算符 (’+’, ‘-’, '’, ‘/’) 组成,中间由一些空格隔开
s 表示一个 有效表达式
表达式中的所有整数都是非负整数,且在范围 [0, 231 - 1] 内
题目数据保证答案是一个 32-bit 整数
题目大意
- 比昨天的每日一题要简单许多,只需要动态维护数据栈和操作符栈就可以了,然后注意当数据栈中只剩一个数且字符栈op的只剩下’-'时,此时符号需要取反
栈
class Solution {
public:
int calculate(string s) {
stack<char> op;
stack<int> nums;
int len = s.size();
for (int i = 0 ; i < len ;){
if(s[i] == ' ') ++i;
if(s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/'){
op.push(s[i]);
++i;
}
if(isdigit(s[i])){
int num = 0;
while(isdigit(s[i])){
num = num * 10 + int(s[i] - '0');
++i;
}
if(!op.empty() && op.top() == '-'){
num *= -1;
op.pop();
op.push('+');
}
nums.push(num);
if(!op.empty() && (op.top() == '*' || op.top() == '/')){
ReallyCalculate(op.top(), nums);
op.pop();
}
}
}
// 当数据栈中只剩一个操作数时出来
while(nums.size() != 1){
ReallyCalculate(op.top(), nums);
op.pop();
}
int ans = nums.top();
if(nums.size() == 1 && !op.empty() && op.top() == '-')
ans *= -1;
return ans;
}
void ReallyCalculate(char op, stack<int>& nums){
int secondNum = nums.top();
nums.pop();
int firstNum = nums.top();
nums.pop();
switch(op){
case '*':
nums.push(firstNum * secondNum);
break;
case '/':
nums.push(firstNum / secondNum);
break;
case '+':
nums.push(firstNum + secondNum);
break;
case '-':
nums.push(firstNum - secondNum);
break;
}
}
};
- 官方的题解
typedef long long ll;
class Solution {
public:
int calculate(string s) {
vector<int> nums;
int len = s.size();
int num = 0;
char op = '+';
for(int i = 0 ; i < len ; ++i){
if(s[i] >= '0' && s[i] <= '9')
num = num * 10 + int(s[i] - '0');
if(!isdigit(s[i]) && s[i] != ' '|| i == len - 1){
switch (op){
case '+':
nums.push_back(num);
break;
case '-':
nums.push_back(-num);
break;
case '*':
nums.back() *= num;
break;
case '/':
nums.back() /= num;
break;
}
num = 0;
op = s[i];
}
}
return accumulate(nums.begin(), nums.end(), 0);
}
};
复杂度分析
- 时间复杂度:O(n)。n为数组的长度
- 空间复杂度:O(n)。n为数组的长度