题目:
实现一个基本的计算器来计算一个简单的字符串表达式 s
的值。
提示:
1 <= s.length <= 3 * 100000
s
由数字、'+'
、'-'
、'('
、')'
、和' '
组成s
表示一个有效的表达式
来源:
解题思路:栈
大致思路:遇到操作符入栈,遇到数字计算后入栈。
- 如果是'+'或'(',操作符入栈
- 如果是'-',操作符入栈,但需要考虑负数的情况,入栈前如果栈空或上一个操作符是'(',则表示一个负数,先补一个0入栈,再入减号,这样转化为0减去一个正数。
- 如果是')',则栈内紧邻必然是'('+数字,pop这2个,再按条件4入栈该数字。
- 如果是数字,有2种情况:(1)第一个数字或'('后第一个数字,直接入栈;(2)否则,pop前一个数字参与计算后再入栈。
用c语言写了一堆goto[汗颜],如下:
typedef struct item {
char type; // 区分+-(或数字
long n;
}Item;
int calculate(char *s){
Item st[150000];
int top = -1;
long curr = 0;
begin:
if (*s == 0) goto end;
if (*s == ' ') {
s++;
goto begin;
}
if (*s == '(' || *s == '+') {
top++;
st[top].type = *s++;
goto begin;
}
if (*s == '-') {
// 前面补0
if (top == -1 || st[top].type == '(') {
top++;
st[top].type = 'd';
st[top].n = 0;
}
top++;
st[top].type = *s++;
goto begin;
}
if (*s == ')') {
curr = st[top].n;
top -= 2;
s++;
goto num;
}
curr = 0;
while (*s >= '0' && *s <= '9') {
curr = curr * 10 + *s - '0';
s++;
}
num:
if (top == -1 || st[top].type == '(') {
top++;
st[top].type = 'd';
st[top].n = curr;
goto begin;
}
if (st[top].type == '+') {
top--;
st[top].n += curr;
goto begin;
}
if (st[top].type == '-') {
top--;
st[top].n -= curr;
goto begin;
}
end:
return top == -1 ? 0 : st[0].n;
}