C solution in 8 ms


  • 0
    F
    //begin: oi is the first integer's position. ni is the empty position.
    //end: oi is the last integer's position. ni is the empty position.
    void eatallinteger(char *orig, int *oi, int *new, int *ni) {
    	int re = orig[*oi] - 48;
    	int i;
    	for (i = *oi + 1; orig[i] > 47 && orig[i] < 58; ++i) {
    		re = re * 10 + orig[i] - 48;
    	}
    	*oi = i - 1;
    	new[(*ni)++] = re;
    }
    
    #include <limits.h>
    //begin: ni is the empty position.
    //end: ni is the empty position.
    void calculateSimple(int *new, int *ni) {
    	int i;
    	int re = 0; 
    	int last = 0;
    	for (i = *ni - 1; new[i] != INT_MAX - 1 && i >= 0; --i) {
    		if (new[i] == INT_MIN) {
    			re -= last;
    			continue;
    		}
    		if (new[i] == INT_MAX) { 
    			re += last;
    			continue;
    		}
    		last = new[i];
    	}
    	re += last;
    	if (i < 0) {
    		new[0] = re;
    		*ni = 1;
    		return;
    	}
    	new[i] = re;
    	*ni = i + 1;	
    }
    
    #include <stdlib.h>
    #include <string.h>
    int calculate(char* orig) {
    	int len = strlen(orig);
    	int *new = calloc(len + 1, sizeof(int));
    	int ni = 0;
    	int i;
    	for (i = 0; orig[i] != '\0'; ++i) {
    		char c = orig[i];
    		if (c == ' ') continue;	
    		else if (c > 47 && c < 58) {
    			eatallinteger(orig, &i, new, &ni);
    		}
    		else if (c == ')') {
    			calculateSimple(new, &ni);
    		}
    		else if (c == '+') {
    			new[ni++] = INT_MAX;
    		}
    		else if (c == '-') {
    			new[ni++] = INT_MIN;
    		}
    		else if (c == '(') {
    			new[ni++] = INT_MAX - 1;
    		}
    		else {
    			exit(-1);
    		}
    	}
    	if (ni != 1) calculateSimple(new, &ni);
    	return new[0];
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.