Simplify Path

本文深入探讨了如何在Unix风格的绝对路径中进行简化操作,包括关键步骤和特殊情况处理,旨在提高路径管理效率。

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

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

click to show corner cases.


直接在path上进行操作,避免额外空间。 
1. 用cwpos代表当前已经写入的index,每当有新的字符需要加入的时候就先递增cwpos,然后写入 (path[++cwpos= X);
2. 用一对偏移表示当前找到的一个介于两个'/'之间的串,cstart和cend(cend也可能是末尾标识'\0')
3. 这样一来clen = cend - cstart就是当前需要附加到返回结果的串(记为s)。 这时分别考虑s为空,s== '.' , s=='..' 以及其他一共四种情况,前两种情况都直接忽略,直接更新cstart = cend进入下次循环; 如果是“..”, 从当前cwpos开始向前找前一个‘/’,并更新cwpos, 如果是其他则写入‘/'和s,同时更新cwpos。



class Solution {
public:
    string simplifyPath(string path) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        int len = path.length();
        int cwpos = -1, cstart = 0, cend = 0;
        while (true) {
            while (cstart < len && path[cstart] == '/') ++cstart;
            if (cstart >= len) break;
            cend = cstart + 1;
            while (cend < len && path[cend] != '/') ++cend;
            int clen = cend - cstart;
            if (clen > 0 && (clen != 1 || path[cstart] != '.')) {
                if (clen == 2 && path[cstart] == '.' && path[cstart + 1] == '.') {
                    while (cwpos >= 0 && path[cwpos] != '/') --cwpos;
                    if (cwpos >= 0)
                        --cwpos;
                } else {
                    path[++cwpos] = '/';
                    while (cstart < cend) {
                        path[++cwpos] = path[cstart++];
                    }
                }
            }
            
            cstart = cend;
        }
        
        if (cwpos < 0) return "/";
        path.resize(cwpos + 1);
        return path;
    }
};


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值