Simplify Path

原题链接

在这里插入图片描述
详细解题思路看代码部分,主要是栈的使用

class Solution {
public:
    
    string simplifyPath(string path) {
        
        int idx = 0;
        //如果有超过2个‘/‘邻近,则去除后一个
        while(idx<path.size()-1){
            if(path[idx]=='/'&&path[idx+1]=='/')path.erase(path.begin()+idx+1);
            else idx++;
        }
        vector<string> vs;//使用堆栈记录每一个有效的子目录
        int n = path.size(),start=1,end =1;
        while(end<path.size()){
            if(path[end]=='/'&&start!=end){//当遇到’/‘时,需要判断是不是'../',若是,则需要出栈;否则判断是不是'./',如果不是则进栈当前子序列path[start,end)
                string tmp = path.substr(start,end-start);
                if(tmp==".."){
                    if(vs.size()) vs.pop_back();
                }
                else if(tmp!=".")vs.push_back(tmp);
                end++;start = end;
            }
            //否则end前进
            else end++;
        }
        //这是是为了应对一种情况,就是path[n-1]不是‘/’时,上面的代码没有处理这种情况,在这里处理
        string p = path.substr(start,end-start);
        if(p ==".."){
            if(vs.size())vs.pop_back();
        }
        else if(path[n-1]!='/'&&p!=".")vs.push_back(p);
        string res = "";
        for(auto s:vs)res+=("/"+s);
        return res==""?"/":res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值