[C]Intuitive Solution with Stack


  • 0
    H
    #define VECTOR_SIZE (1024)
    char* simplifyPath(char* path) {
        char** stack = malloc(sizeof(char*)*1024);
        if(path == NULL || *path=='\0') return path;
        if(path[0] != '/') path[0] = '/';
        char* word;
        char* sep = "/";
        int stk_pos = 0;
        int ret_s_len = 0;
        for(word = strtok(path,sep); word; word = strtok(NULL,sep)) {
            if(0 == strcmp(".", word)) continue;
            if(0 == strcmp("..", word)) {
                if(stk_pos > 0) stk_pos--;
                continue;
            }
            stack[stk_pos++] = strdup(word);
            ret_s_len += strlen(word);
        }
    
        char* ret_s = malloc(ret_s_len + stk_pos - 1 + 2);
        if(stk_pos == 0) {
            ret_s[0] = '/';
            ret_s[1] = '\0';
            return ret_s;
        };
        int pos = 0;
        int str_len;
        for(int i = 0; i < stk_pos; i++) {
            ret_s[pos++] = '/';
            str_len = strlen(stack[i]);
            memcpy(ret_s + pos, stack[i], str_len);
            pos += str_len;
        }
        ret_s[pos] = '\0';
    
    
        return ret_s;
    }
    

Log in to reply
 

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