My C solution on gcc and Visual Studio can pass, but not by our oj


  • 0
    H
    typedef struct stack {
    	char ch;
    	struct stack *prev;
    } stack;
    
    stack *top = NULL;
    
    void push(char ch) {
    	if (!top) {
    		top = (stack *)malloc(sizeof(stack));
    		top->ch = ch;
    		top->prev = NULL;
    	} else {
    		stack *p = (stack *)malloc(sizeof(stack));
    		p->ch = ch;
    		p->prev = top;
    		top = p;
    	}
    }
    
    void pop() {
    	stack *p = top;
    	top = top->prev;
    	free(p);
    }
    
    char getTop() {
    	return top == NULL ? '\0' : top->ch;
    }
    
    int find(char *s, char ch) {
    	for (int i = 0; i < strlen(s); i++) {
    		if (s[i] == ch)
    			return i;
    	}
    	return -1;
    }
    
    bool isValid(char *s) {
        char *left = "([{";
        char *right = ")]}";
    
        for (int i = 0; i < strlen(s); i++) {
        	if (find(left, s[i]) != -1) {
        		push(s[i]);
        	} else {
        		if (getTop() != left[find(right, s[i])] || !top)
        			return false;
        		else
        			pop();
        	}
        }
    	return NULL == top ? true : false;
    }

Log in to reply
 

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