[LeetCode] Simplify Path

路径简化算法详解
本文深入探讨了如何将Unix风格的绝对路径进行简化的过程,通过分析并实现两种不同的算法,旨在帮助开发者更高效地处理文件路径相关的问题。

Given an absolute path for a file (Unix-style), simplify it.

For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

 

字符串最麻烦~折腾

class Solution {
public:
    void getnext(const string& str, int& start, int& end) {
        while (start < str.size() && str[start] == '/') start++;
        if (start == str.size()) {start =-1; return;}
        end = start;
        while (end < str.size() && str[end] != '/') end++;
    }

    string simplifyPath(string path) {
        char* a = new char[path.size()];
        memset(a, 0, path.size());
        int pos = 0, end = 0;
        
        while (end < path.size()) {
            getnext(path, pos, end);
            if (pos == -1) break;
            int l = end - pos;
            string sub = path.substr(pos, l);
            if (sub.compare(".") == 0) {
            } else if (sub.compare("..") == 0) {
                int last = strlen(a) - 1;
                while (last >= 0 && a[last] != '/') last--;
                if(last < 0) a[0] = '\0';
                else a[last] = '\0';
            } else {
                strcat(a, "/");
                strcat(a, sub.c_str());
            }
            pos = end + 1;
        }
        if (strlen(a) == 0) {a[0] = '/'; a[1] = '\0';}
        string res(a);
        delete []a;
        return res;
    }
};

 

 

class Solution {
public:
    string simplifyPath(string path) {
        int n = path.size();
        auto& a = path;
        if (n == 0) return path;
        
        char *c = new char[n+1];
        memcpy(c, path.c_str(), n+1);
        
        int idx = 0;
        char *s = c, *e;
        while (*s != '\0') {
            s = getFirst(s);
            e = getLast(s);
            if (*s == '\0') break;
            if (e == s && *s == '.') s = e + 1;
            else if (e - s == 1 && *s == '.' && *e == '.') {
                if (idx > 0)
                    idx = up(c, idx-1);
                s = e+1;
            }
            else {
                c[idx++] = '/';
                while (s <= e) c[idx++] = *s++;
            }
        }
        if (idx == 0) c[idx++] = '/';
        c[idx] = '\0';
        return string(c);
    }
    
    int up(char*c, int i) {
        while (i > 0 && c[i] != '/') i--;
        return i;
    }
    char* getFirst(char *c) {
        while (*c == '/') c++;
        return c;
    }
    char* getLast(char * c) {
        while (*c != '/' && *c != '\0') c++;
        return c-1;
    }

};

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值