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;
    }
};

 

posted @ 2018-06-10 06:46  妖域大都督  阅读(106)  评论(0编辑  收藏  举报