zoukankan      html  css  js  c++  java
  • 【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]] = '';
        return (*s)?s :"/";
    }
  • 相关阅读:
    hdu 2222 Keywords Search
    Meet and Greet
    hdu 4673
    hdu 4768
    hdu 4747 Mex
    uva 1513 Movie collection
    uva 12299 RMQ with Shifts
    uva 11732 strcmp() Anyone?
    uva 1401
    hdu 1251 统计难题
  • 原文地址:https://www.cnblogs.com/ganxiang/p/14122812.html
Copyright © 2011-2022 走看看