C Solution NOT using Stack


  • 0
    U

    Use recursion. 3ms runtime

    #include <string.h>
    
    int check(char** cur, char paren)
    {
        if(!**cur) return 0;
        switch(*(*cur)++)
        {
            case '(' : return check(cur, '(') ? check(cur, paren): false;
            case '[' : return check(cur, '[') ? check(cur, paren): false;
            case '{' : return check(cur, '{') ? check(cur, paren): false;
            case '<' : return check(cur, '<') ? check(cur, paren): false;
            case ')' : return paren == '(' ? true: false;
            case ']' : return paren == '[' ? true: false;
            case '}' : return paren == '{' ? true: false;
            case '>' : return paren == '<' ? true: false;
        }
        return 0;
    }
    
    
    
    bool isValid(char* s) {
        char* temp = (char*) malloc(strlen(s)+3);
        temp[0] = '<';
        
        strcat(temp,s);
        strcat(temp,">");
        char paren = *temp;
        temp++;
        return check(&temp,paren);
    }
    

Log in to reply
 

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