0 ms C solution with stack


  • 0
    M

    #define TDIR (0)
    #define TFILE (1)
    #define MAX_ITEM 100

    char *get_next_item(char *start, int *ideep, int *ilen, int *type)
    {
    int i = 0;

    *ideep = 0;
    *ilen = 0;
    *type = TDIR;
    
    while (start[i] != 0) {
        if (start[i] == '\n') {
            break;
        }
        if (start[i] == '\t') {
            (*ideep) ++;
        } else {
            (*ilen) ++;
        }
    
        if (start[i] == '.') {
            *type = TFILE;
        }
        i ++;
    }
    
    return (start + (*ideep));
    

    }

    int lengthLongestPath(char* input) {
    char *item;
    char *start;
    int deep[MAX_ITEM];
    int len[MAX_ITEM];
    int sp = 0;
    int max_len = 0;
    int temp;
    int ideep;
    int ilen;
    int end = 0;
    int type;

    start = input;
    deep[sp] = -1;
    len[sp] = 0;
    
    do {
        item = get_next_item(start, &ideep, &ilen, &type);
        while (ideep <= deep[sp]) {
            sp --;
        }
    
        if (item[ilen] == 0) {
            end = 1;
        }
        item[ilen] = 0;
    
        if (type == TDIR) {
            sp ++;
            deep[sp] = ideep;
            len[sp] = len[sp - 1] + ilen + 1;
        } else {
            temp = len[sp] + ilen;
            if (temp > max_len) {
                max_len = temp;
            }
        }
        start = item + ilen + 1;
    } while (!end);
    
    return max_len;
    

    }


Log in to reply
 

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