题意
实现一个计算器 +, -, *, /,给定字符串计算出结果
链接
https://leetcode.com/problems/basic-calculator-ii/description/
思考
首先看到这道题我们需要知道*
,/
是优先于+
, -
所以我们需要一个数据结构去维护这个性质(hashmap),计算器一般都是维护数字栈和运算符号栈。
题解
构造两个栈,数字栈和运算符号栈, 一个包含运算符号优先级的hashmap。
遍历字符串,遇到数,把数字放入数字栈
遇到运算符号,如果放入的元素的优先级小于等于运算符号栈顶元素的优先级,运算符号栈pop出来,数字栈pop出栈顶两个元素x和y,计算结果后把结果放入数字栈。
遍历结束运算符号栈不一定为空,所以需要不断pop 运算符号栈和数字栈计算答案。
注意
- pop操作符的时候,操作符栈顶元素的优先级者和当前元素一样也要pop出来
- 比如 3/ 2, 和 3-2, 3是先进入栈的元素,2是后进入栈的元素,所以计算的时候要弄清楚顺序
模版总结
截取字符串模版
for(int i = 0; i < s.size(); i++) {
if(isdigit(s[i])) {
int j = i;
while(j < s.size() && isdigit(s[j])) j++;
int x = stoi(s.substr(i, j-i));
num.push(x);
i = j - 1;
}
}
注意substr(字符串起点,有多少位)
解法
class Solution {
public:
int calculate(string s) {
stack<int> num;
stack<char> oper;
unordered_map<char, int> pr = {{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}};
for(int i = 0; i < s.size(); i++) {
if(isdigit(s[i])) {
int j = i;
while(j < s.size() && isdigit(s[j])) j++;
int x = stoi(s.substr(i, j-i));
num.push(x);
i = j - 1;
} else if(pr.count(s[i])) {
while(oper.size() && pr[s[i]] <= pr[oper.top()]) {
get(num, oper);
}
oper.push(s[i]);
} else if(s[i] == ' ') {
continue;
} else if (s[i] == '(') {
oper.push(s[i]);
} else if (s[i] == ')') {
while(oper.top()!= '(') {
get(num, oper);
}
oper.pop();
}
}
while(oper.size()) {
get(num, oper);
}
return num.top();
}
void get(stack<int>& num, stack<char>& oper) {
int num1 = num.top();
num.pop();
int num2 = num.top();
num.pop();
char op = oper.top();
oper.pop();
int result = 0;
switch(op) {
case '*': result = num1 * num2; break;
case '+': result = num1 + num2; break;
case '-': result = num2 - num1; break;
case '/': result = num2 / num1; break;
}
num.push(result);
}
};
时间复杂度:
O
(
n
)
O(n)
O(n) n位字符串长度
空间复杂度:
O
(
n
+
4
)
O(n+4)
O(n+4) 字符串长度+额外的优先级表