71.简化路径

1、简化路径
在这里插入图片描述在这里插入图片描述
思路: 以段为单位来处理。
代码1

class Solution {
public:
    string simplifyPath(string path) {
        path += "/";		//方便处理不以 `/`结尾的path
        string res, s;	// res为返回结果,s 为当前段
        for(auto c : path)
        {
            if(res.empty()) res += c;		//第一次先把 '/'存进去
            else if(c != '/')   s += c;
            else
            {
                if(s == "..")			//要去掉上一层 比如当前 res = "/home/" , s = ".." ; --->   res = "/";
                {
                    if(res.size() > 1)		//是不是最顶层
                    {
                        res.pop_back();		//去掉结尾的 '/'
                        while(res.back() != '/')  	// 去掉上层文件夹名,比如这里的 "home"
                        	res.pop_back();	
                    }
                }
                else if(s != "" && s != ".")		//如果是空或者'.' 就不加进去
                    res +=  s + '/' ;
                s = "";			//清空 s
            }
        }
        if(res.size() > 1) res.pop_back();	//把最后的 '/'去掉
        return res;
    }
};

代码2
在这里插入图片描述

class Solution {
public:
    string simplifyPath(string path) {
        string res, t;		//t 为当前段
        stringstream ss(path);
        vector<string> v;		
        while (getline(ss, t, '/')) {
            if (t == "" || t == ".") continue;
            if (t == ".." && !v.empty()) v.pop_back();	//上一段去掉
            else if (t != "..") v.push_back(t);
        }
        for (string s : v) res += "/" + s;
        return res.empty() ? "/" : res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值