其他分享
首页 > 其他分享> > 【leetcode】71. 简化路径

【leetcode】71. 简化路径

作者:互联网

 

char * simplifyPath(char * path){
    char *stack[100];
    int size = 0;
    for (char *s = strtok(path, "/"); s; s = strtok(NULL, "/")) {
        if (strcmp(s, ".") == 0) {
            //do nothing
        } else if (strcmp(s, "..") == 0) {
            //back 
            size = fmax(0, size-1);
        } else {
            stack[size++] = s;
        }
    }
    if (size == 0) return "/";
    char *res = calloc(1000, sizeof(char));
    for (int i=0; i<size; ++i) {
        strcat(res, "/");
        strcat(res, stack[i]);
    }
    return res;
}

 

char * simplifyPath(char * path){
    int len = strlen(path), i, left=0, pst=0;
    char* s = (char*)calloc(len+1, sizeof(char));
    int end[100] = { 0 };
    for (i = 0; i < len; i++){
        if (i + 1<len && path[i] == '/' && path[i+1] != '/'){
            left = i;
            if (i + 1 < len &&  path[i + 1] == '.' && ( i+2 >= len || path[i+2] == '/') ){
                i += 1;
            }
            else if (i + 1 < len &&  path[i + 1] == '.' && i + 2 < len && path[i + 2] == '.' && (i + 3 >= len || path[i + 3] == '/') ){
                if (pst > 0) pst--;
                i += 2;
            }
            else{
                while (i+1 < len && path[i + 1] != '/')
                    i++;
                memcpy(s + end[pst], path + left, i - left + 1);
                end[pst + 1] = end[pst] + i - left + 1;
                pst++;
            }
        }
    }
    s[end[pst]] = '\0';
    return (*s)?s :"/";
}

 

标签:&&,len,char,简化,71,path,leetcode,pst,size
来源: https://www.cnblogs.com/ganxiang/p/14122812.html