[Stack] [leetcode] [Difficulty] 224. Basic calculator

topic:

Implement a basic calculator to calculate the value of a simple string expression  s .

prompt:

  • 1 <= s.length <= 3 * 100000
  • s By the '+'numbers, '-', '(', , ')', and  ' ' make up
  • s Represents a valid expression

source:

224. Basic calculator

Problem-solving ideas: stack

General idea: When encountering an operator, it is pushed into the stack, and when it encounters a number calculation, it is pushed into the stack.

  1. If it is '+' or '(' , the operator is pushed onto the stack
  2. If it is'- ' , the operator is put on the stack, but the case of negative numbers needs to be considered. If the stack is empty or the previous operator is '(' before being put on the stack , it means a negative number, first add a 0 to the stack, and then enter the minus sign , Which is converted to 0 minus a positive number.
  3. If it is ')' , the next to the stack must be '(' + number, pop these two, and then push the number into the stack according to condition 4).
  4. If it is a number, there are two situations: (1) The first number or the first number after '(' is directly pushed into the stack; (2) Otherwise, the previous number is popped into the stack after participating in the calculation.

Wrote a bunch of goto [shame] in C language, as follows:

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;
}

Guess you like

Origin blog.csdn.net/hbuxiaoshe/article/details/114636807