A 1ms C solution


  • 0
    G
    bool isValidOpeningParenthesis(char curChar) {
        return (curChar == '(' || curChar == '{' || curChar == '[');
    }
    
    bool isValidClosingParenthesis(char curChar) {
        return (curChar == ')' || curChar == '}' || curChar == ']');
    }
    
    bool doesClosingMatchOpening(char closing, char opening) {
        if (closing == ')') {
            return (opening == '(');
        }
        if (closing == ']') {
            return (opening == '[');
        }
        if (closing == '}') {
            return (opening == '{');
        }
    }
    
    bool isValid(char* s) {
        char *parStack = malloc(sizeof(char)*17);
        int count = 0;
        int max = 17;
        while (*s != 0) {
            char curChar = *s;
            if (!isValidOpeningParenthesis(curChar) && !isValidClosingParenthesis(curChar)) {
                s++;
                continue;
            }
            else if (isValidOpeningParenthesis(curChar)) {
                parStack[count] = curChar;
                count++;
                if (count >= max) {
                    parStack = realloc(parStack, sizeof(char)*2*max);
                    max *= 2;
                }
            }
            else {
                if (!doesClosingMatchOpening(curChar,parStack[count-1])) {
                    return false;
                }
                parStack[count] = 0;
                count--;
            }
            s++;
        }
        return (count == 0);
    }
    

    Yeah, it's long, but I hope it's readable. It's just a stack implemented with a dynamic array instead of some built-in data structure.


Log in to reply
 

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