C solution, run time error appears for some test cases while submit


  • 0
    O

    Why my code get Run Time Error when I tried to submit, but got the correct result when I was doing Run Code for the failed cases?

    Can someone please help me out? Thanks

    char* simplifyPath(char* path) {
        int len = strlen(path);
        char* result = (char*)malloc(len*sizeof(char));
        char* temp = (char*)malloc(len*sizeof(char));
        int i, dot = 0, x = 0;
        int go_up = 0;
        for(i = len-1; i >= 0; i--){
            if(path[i] == '/'){
                if(x == 0) continue;
                if(dot == 2) go_up++;
                if(go_up != 0){
                    strcat(result, "/");
                    if(dot != 2 && !(x == 1 && dot == 1)) go_up--;
                }
                else{
                     if(!(x == 1 && dot == 1)) strcat(result, temp);
                    strcat(result, "/");
                }
                memset(temp, '\0', len*sizeof(char));
                x = 0;
                dot = 0;
            }
            else{
                if(path[i] == '.') dot++;
                else{
                    dot = 0;
                }
                temp[x] = path[i];
                x++;
            }
        }
        // reverse path
        len = strlen(result);
        //printf("%s", result);
        char* rPath = malloc(len*sizeof(char));
        x = 0;
        bool needSlash = true;
        for(i = len - 1; i >= 0; i--){
            if(result[i] == '/'){
                if(needSlash) {
                    rPath[x] = result[i];
                    needSlash = false;
                    x++;
                }
            }
            else{
                needSlash = true;
                rPath[x] = result[i];
                x++;
            }
        }
        if(rPath[x-1] == '/') rPath[x-1] = '\0';
        return rPath;
    }
    

Log in to reply
 

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