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 .
Example 1:
Input: "1 + 1" Output: 2
Example 2:
Input: " 2-1 + 2 " Output: 3
Example 3:
Input: "(1+(4+5+2)-3)+(6+8)" Output: 23
Note:
- You may assume that the given expression is always valid.
- Do not use the
eval
built-in library function
题意:给出一个只有+-()和非负数的合法表达式,计算这个表达式的值。
思路:大体思路是每次遇到的如果不是),就入栈,遇到),执行出栈操作,直到遇到(,出栈过程中结算这个括号里的表达式的值,然后把这个值在入栈,写起来细节还是挺多的。
C代码:
int calculate(char* s) {
int i,len,top,j;
long long stack[100005],temp1,temp2,res;
const long long op1 = (long long)INT_MAX + 1,op2 = op1 + 1,op3 = op2 + 1;
res = top = 0;
len = strlen(s);
for(i = 0; i < len; i++) {
if(s[i] == '(') {
stack[top++] = op3;
}
else if(s[i] == '+') {
stack[top++] = op2;
}
else if(s[i] == '-') {
stack[top++] = op1;
}
else if(s[i] >= '0' && s[i] <= '9') {
temp1 = 0;
for(j = i; s[j] >= '0' && s[j] <= '9'; j++) {
temp1 = temp1 * 10 + s[j] - '0';
}
stack[top++] = temp1;
i = j - 1;
}
else if(s[i] == ')') {
temp1 = 0;
temp2 = 0;
top--;
while(stack[top] != op3) {
if(stack[top] < op1) {
temp1 = stack[top];
}
else {
if(stack[top] == op1) temp2 -= temp1;
else if(stack[top] == op2) temp2 += temp1;
}
top--;
}
stack[top++] = temp2 + temp1;
}
}
int flag = 1;
for(i = 0; i < top; i++) {
if(stack[i] == op2) flag = 1;
else if(stack[i] == op1) flag = -1;
else res += flag * stack[i];
}
return res;
}