题目:
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
- 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"
.
#include<iostream>
#include<string>
#include<stack>
using namespace std;
string simplifyPath(string path)
{
int len=path.length();
string temp="";
stack<string> ss;
for(int i=0;i<len;i++)
{
if(path[i]=='/')
{
if(temp=="..")
{
if(!ss.empty())
ss.pop();
}
else if(temp!="."&&temp!="")
{
ss.push(temp);
}
temp="";
}
else
{
temp=temp+path[i];
}
}
if(temp=="..")//此处添加是类似于"/ac/..."的输出是"/ac/..."
{
if(!ss.empty())
ss.pop();
}
else if(temp!="."&&temp!="")
{
ss.push(temp);
}
if(ss.empty())
{
return "/";
}
string res="";
while(!ss.empty())
{
res="/"+ss.top()+res;
ss.pop();
}
return res;
}
int main()
{
string path="/a/./b/../../c/"; //"/..."注意此类的输出
string result=simplifyPath(path);
cout<<result<<endl;
return 0;
}