4ms C Solution with O(1) Space


  • 0
    A
    char* simplifyPath(char* path) {
        int i, t=1;
    	int len = strlen(path);
    	path[0] = '/';
        for(i=1; i<len; i++) {
            if(path[i]=='.' && ((i+1<len && path[i+1]=='/') || path[i+1]=='\0')) {
                i = i + 1;
            } else if(path[i]=='.' && i+1<len && path[i+1]=='.' && ((i+2<len && path[i+2]=='/') || path[i+2]=='\0')) {
                i = i + 2;
                t = t - 2 < 0? 0: t-2;
                while(path[t]!='/') {
                    t--;
                }
    			t++;
            } else if(path[i]=='/') {
    			continue;
    		} else {
                do {
                    path[t++] = path[i++];
                } while(i<len && path[i]!='/');
                path[t++] = path[i];
            }
        }
    	if(t>1) {
    		path[t-1] = '\0';
    	} else {
    		path[t] = '\0';
    	}
    	return path;
    }

Log in to reply
 

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