第一周 leetcode 224. Basic Calculator(hard)
题目描述:
Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .
You may assume that the given expression is always valid.
Some examples:
“1 + 1” = 2
” 2-1 + 2 ” = 3
“(1+(4+5+2)-3)+(6+8)” = 23
Note: Do not use the eval built-in library function.
解题思路:
需要维护一个数字栈和一个操作符栈,将字符串遍历一遍实现计数器的功能:
1. 如果+,-,(就直接入操作符栈;
2.如果是数字,看操作符栈:
a.如果操作符栈顶是+、-,把该元素和数字栈顶元素进行相应运算并存入数字栈顶;
b.否则直接将该数字入栈;
3.如果是),直接把操作符栈栈顶元素给弹出,因为栈顶元素必然是(,然后将操作符栈和数字栈进行运算,直到不能运算为止;
4.注意数字位数可能大于1;
5.注意跳过空格;
代码:
class Solution {
public:
int calculate(string s) {
stack<int> operand; // 数字栈
stack<char> ch; // 操作符栈
int n = 0;
while(n < s.size()) { // 遍历字符串
if (isspace(s[n])) {
// 空格跳过
n ++;
continue;
}
if (isdigit(s[n])) {
// 读数字
int num = 0;
while(n < s.size() && isdigit(s[n])) {
num = 10 * num + s[n] - '0';
n ++;
}
if (ch.empty() || ch.top() == '(') operand.push(num);
else if (ch.top() == '+') {
num = operand.top() + num;
operand.pop();
ch.pop();
operand.push(num);
}
else {
num = operand.top() - num;
operand.pop();
ch.pop();
operand.push(num);
}
}
else {
if (s[n] == ')') {
ch.pop();
while (ch.size() && ch.top() != '(') {
int operand1 = operand.top(); operand.pop();
int operand2 = operand.top(); operand.pop();
if (ch.top() == '+') operand.push(operand1 + operand2);
else operand.push(operand2 - operand1);
ch.pop();
}
}
// 其他操作符,则直接入操作符栈
else ch.push(s[n]);
n ++;
}
}
return operand.top();
}
};
代码运行结果: