71. Simplify Path

Posted yaoyudadudu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了71. Simplify Path相关的知识,希望对你有一定的参考价值。

问题描述:

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".

 

解题思路:

我一开始想的是可以以‘/’作为分隔符来读取字符串,但是没有什么合适的方法。

看了大神的方法,用了stringstream类:官方文档

这里需要注意的是:

/..:返回上级目录,所以需要删掉前一个目录名

/. :当前目录

 

代码:

class Solution {
public:
    string simplifyPath(string path) {
        string ret, temp;
        stringstream ss(path);
        vector<string> p;
        while(getline(ss, temp, /)){
            if(temp == "" || temp==".") 
                continue;
            if(temp == ".." && !p.empty())
                p.pop_back();
            else if(temp != "..")
                p.push_back(temp);
        }
        for(string str : p){
            ret += "/" + str;
        }
        return ret.empty() ? "/" : ret;
    }
};

 





以上是关于71. Simplify Path的主要内容,如果未能解决你的问题,请参考以下文章

71. Simplify Path

leetcode 71 Simplify Path

71. Simplify Path

71. Simplify Path

71. Simplify Path

71. Simplify Path