Leetcode 227 Basic calculator II
https://leetcode.com/problems/basic-calculator-ii/description/
题意:实现一个计算器 +, -, *, /
首先看到这道题我们需要知道*
,/
是优先于+
, -
所以我们需要一个数据结构去维护这个性质(hashmap)。算法思路是扫描数组先把数放进一个栈,把操作符放进另一个栈,每当遇到操作符,并且操作符栈顶元素的优先级要比我当前元素大了或者和当前元素一样,那需要优先计算(因为你从左到右扫描数组),pop出来进行计算。
比较容易错的点:
- pop操作符的时候,操作符栈顶元素的优先级者和当前元素一样也要pop出来
- 比如 3/ 2, 和 3-2, 3是先进入栈的元素,2是后进入栈的元素,所以计算的时候要弄清楚顺序
- 当你要得到一个字符串中的数字时,i++的最后需要i–,因为最后一位数字得到了,你的i已经跑到下一位不是数字的上面去了
class Solution {
public:
int calculate(string s) {
stack<char> oper;
stack<int> number;
unordered_map<char, int> mp = {{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}};
int i = 0;
for (; i < s.size(); i++) {
if (s[i] == ' ') {
continue;
}
if (s[i] >= '0' && s[i] <= '9') {
int x = 0;
while(i < s.size() && s[i] >= '0' && s[i] <= '9') {
x = x * 10 + (s[i] - '0');
i++;
}
i--;
number.push(x);
}
else {
while(!oper.empty() && mp[oper.top()] >= mp[s[i]]) {
int number1 = number.top();
number.pop();
int number2 = number.top();
number.pop();
char op = oper.top();
oper.pop();
number.push(applyOp(number2, number1, op));
}
oper.push(s[i]);
}
}
while(!oper.empty()) {
int number1 = number.top();
number.pop();
int number2 = number.top();
number.pop();
char op = oper.top();
oper.pop();
number.push(applyOp(number2, number1, op));
}
return number.top();
}
int applyOp(int x, int y, char op) {
if (op == '+') {
return x + y;
}
if (op == '-') {
return x - y;
}
if (op == '*') {
return x * y;
}
if (op == '/') {
return x / y;
}
return 0;
}
};