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".
思考:不断提交修改。。
class Solution {
public:
string simplifyPath(string path) {
// ..上一级目录
// .当前目录
// 根目录下..和.相同
string ans="";
vector<string> p; //记录每一级目录
string temp;
int len1=path.size();
int i;
for(i=0;i<len1;i++)
{
if(path[i]=='/')
{
if(temp=="") continue;
else if(temp=="..")
{
if(p.empty()) temp=""; //根目录
else
{
p.pop_back(); //返回上一级目录
temp="";
}
}
else if(temp==".") temp="";
else
{
p.push_back(temp);
temp="";
}
}
else temp+=path[i];
}
if(temp!=""&&temp!=".")
{
if(temp=="..")
{
if(!p.empty())
p.pop_back();
}
else p.push_back(temp);
}
int len2=p.size();
if(len2==0) return "/";
for(i=0;i<len2;i++) ans+='/'+p[i];
return ans;
}
};