71. Simplify Path

本文介绍了一种Unix风格文件路径简化的算法实现。通过使用字符串流和向量来处理路径中的各种特殊情况,如忽略当前目录'.'、返回上级目录'..'及多余的斜杠。最终返回规范化的绝对路径。

Description:

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

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

Corner Cases:

  • Did you consider the case where path = "/../"?
    In this case, you should return "/".
  • Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
    In this case, you should ignore redundant slashes and return "/home/foo".
分析:此题是将Unix-style的路径简化,即将相对路径转化为绝对路径。这道题看着简单,过程十分艰辛。传统的一个个字符读取处理情况太过复杂,写出来的代码凌乱不堪。接下来说一下正确思路,建立一个string的数组res,以“/”为分隔符将path中路径分割存储。如果遇到".",不存储;遇到“..”,若res为空,则不做处理,若不为空,则删除res的最后一个元素。(res的作用类似于栈)。

下面贴的是按照discuss上一个小哥思路的代码:(getline()的用法参照我的博文http://blog.csdn.net/anonymouscrawler/article/details/78900744

class Solution {
public:
    string simplifyPath(string path) {
        string res, tmp;
        vector<string> spilt;
        stringstream ss(path);
        
        while(getline(ss, tmp, "/")
        {
            if(tmp == "." || tmp == "")   //为什么需要判断tmp=="",参考上面链接.
                continue;
            
            if(tmp == ".." && !spilt.empty())
                spilt.pop_back();
            else if(tmp != "..")
                spilt.push_back(tmp);
        }
        
        for(auto str : spilt)
            res = res + "/" + str;
        
        if(res.empty())
            return "/";
        else
            return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值