Simplify Path

来源:互联网 发布:通用电气知乎 编辑:程序博客网 时间:2024/06/03 06:00

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

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

click to show corner cases.

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".
一道考察细节的题目,但是这个的test case不全,没有考虑../../的情况。


分析:

1. path的分界符为 “/", 所以可以以slash为区分。

2. 当两个/中间为空或者为.的时候,则可忽略

3. 当两个中间为..的时候,则抹掉上一次层

4. 其他为合法, push back


左后返回结果的时候要注意如果为空的话需要返回一个'/'。 

所以整个就是维护一个stack,然后考虑三种情况,最后返回一个以'/'为头的string.  比较tricky的是getline(stringstream(path), tmp, '/'). 这个是基本功,但是没想到。学习了


class Solution {public:    string simplifyPath(string path) {    string res,tmp;    stringstream ss(path);    vector<string> stk;    while(getline(ss,tmp,'/')){    if (tmp=="." || tmp=="")    continue;    if (tmp==".." && !stk.empty()){    stk.pop_back();    }    if (tmp!="..")    stk.push_back(tmp);    }    for (int i=0; i<stk.size(); i++){    res+="/"+stk[i];    }    return res.empty()? "/":res;    }};



0 0