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 :"/";
    }
  • 相关阅读:
    LYDSY模拟赛day3 序列
    LYDSY模拟赛day3 涂色游戏
    LYDSY模拟赛day3 平均数
    hdu1757 A Simple Math Problem
    清北国庆day1 (脑)残
    poj3070 Fibonacci
    uva10870 递推关系Recurrences
    湖南附中模拟day1 瞭望塔
    湖南附中模拟day1 收银员
    湖南附中模拟day1 金坷垃
  • 原文地址:https://www.cnblogs.com/ganxiang/p/14122812.html
Copyright © 2011-2022 走看看