link
https://leetcode-cn.com/problems/basic-calculator-ii/
time consuming
Problem solving: 40 min
Problem solving: 25 min
Title
Give you a string expression s, please implement a basic calculator to calculate and return its value.
Integer division only retains the integer part.
prompt:
- 1 <= s.length <= 3 * 105
- s is composed of integers and operators ('+','-','*','/'), separated by some spaces
- s represents a valid expression
- All integers in the expression are non-negative integers and are in the range [0, 231-1]
- The question data guarantees that the answer is a 32-bit integer
Ideas
According to the meaning of the question, there are only two priority levels,'+','-' and'*','/'. Among them, the priority of multiplication and division is higher. So a simple idea is to first calculate the part with multiplication and division, and finally to traverse and calculate only the expression of addition and subtraction.
In order to be able to traverse by pressing the index at the end, I used a double-ended queue, but used the idea of a stack.
Set up two stacks, a symbol stack and a number stack. Traverse the string, if the current is a plus or minus sign, add it to the symbol stack, if it is a number, add it to the number stack, if it is a multiplication and division sign, first get the first number after the multiplication and division sign and the top element of the number stack, and pop it out, then Multiply and divide the sum of the top element on the stack by this number and push it onto the stack. After one traversal, multiplication and division are no longer included, and another traversal adds and subtracts the elements in the number stack to the result according to the symbol stack.
Time complexity: O (n) O(n)O ( n )
AC code
class Solution {
public:
int calculate(string s) {
deque<int> symbol;
deque<int> nums;
if(s[0] == '-') symbol.push_back(-1);
else symbol.push_back(1);
int n = s.size();
for(int i = 0; i < n; ++i) {
if(s[i] == ' ') {
continue;
}
else if(s[i] == '+') {
symbol.push_back(1);
}
else if(s[i] == '-') {
symbol.push_back(-1);
}
else if(s[i] == '*') {
while(!(s[i] >= '0' && s[i] <= '9')) i++;
int num2 = 0;
while(s[i] >= '0' && s[i] <= '9') {
num2 = num2*10 + (s[i]-'0');
i++;
}
i--;
int num1 = nums.back();
nums.pop_back();
nums.push_back(num1*num2);
}
else if(s[i] == '/') {
while(!(s[i] >= '0' && s[i] <= '9')) i++;
int num2 = 0;
while(s[i] >= '0' && s[i] <= '9') {
num2 = num2*10 + (s[i]-'0');
i++;
}
i--;
int num1 = nums.back();
nums.pop_back();
nums.push_back(num1/num2);
}
else {
int num = 0;
while(s[i] >= '0' && s[i] <= '9') {
num = num*10 + (s[i]-'0');
i++;
}
i--;
nums.push_back(num);
}
}
int ans = 0;
for(int i = 0; i < nums.size(); ++i) {
ans += symbol[i]*nums[i];
}
return ans;
}
};