class Solution {
public:
string simplifyPath(string path) {
stack<string> fileName;
string curFileName;
for(int i=0;i<path.size();++i)
{
if(path[i]=='/')
{
if(curFileName.size()>0)
{
if(curFileName==".")
{
//
}
else if(curFileName=="..")
{
if(!fileName.empty())
{
fileName.pop();
}
}
else
{
fileName.push(curFileName);
}
}
curFileName="";
}
else
{
curFileName.append(1,path[i]);
}
}
if(curFileName.size()>0)
{
if(curFileName==".")
{
//
}
else if(curFileName=="..")
{
if(!fileName.empty())
{
fileName.pop();
}
}
else
{
fileName.push(curFileName);
}
}
/*
//follwing code is ok,but because insert at the string begining cost liner time, so we could make it better
string res;
while(!fileName.empty())
{
res.insert(0,fileName.top());
fileName.pop();
res.insert(0,1,'/');
}
if(res.size()==0)
{
res.insert(0,1,'/');
}
*/
//transform from stack to vector to speed up
vector<string> tmp;
while(!fileName.empty())
{
tmp.push_back(fileName.top());
fileName.pop();
}
if(tmp.size()==0)
{
return "/";
}
string res;
for(int i=tmp.size()-1;i>=0;--i)
{
res.append(1,'/');
res.append(tmp[i]);
}
return res;
}
};
基本思路,用栈来追溯文件路径中的文件名,这样可以很容易处理" . "和“ .. ”这两种特殊情况