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".
此题刚开始看着比较懵逼,不知道怎么求解,但是慢慢想想其实还是很简单的,可以忽略 ./ (代表当前目录),遇到 ../ 代表上一层目录,可以在对目录遍历的过程中不断的保存当前合法的路径,然后遇到 ../ 将当前路径弹出一个文件夹即可。
string simplifyPath(string path) {
vector<string> res;
for (auto it = path.begin(); it != path.end();){
it++;
auto j = find(it, path.end(), '/');
string str = string(it, j);
if (!str.empty() && str != "."){
if (str == ".."){
if (!res.empty())res.pop_back();
}
else res.push_back(str);
}
it = j;
}
ostringstream out;
if (res.empty())out << '/';
else
for (auto x : res)out << '/' << x;
return out.str();
}