直接用栈模拟一下即可。
class Solution {
public:
string simplifyPath(string path) {
int n=path.size();
if(n==0) return "";
stack<string> sta;
int k=0;
while(path[k]!='/') k++;
string tmp;
tmp.push_back(path[k]);
sta.push(tmp);
while(path[k]=='/') k++;
while(k<n)
{
tmp="";
while(k<n&&path[k]!='/')
{
tmp.push_back(path[k]);
k++;
}
if(k<n) {
tmp.push_back(path[k]);
k++;
}
if(tmp=="../"||tmp=="..")
{
string tp=sta.top();
if(tp!="/")
{
sta.pop();
}
}
else if(tmp=="./"||tmp=="."||tmp=="/")
{
}
else
{
sta.push(tmp);
}
while(k<n&&path[k]=='/') k++;
}
stack<string> tm;
while(sta.empty()==0)
{
tm.push(sta.top());
sta.pop();
}
string ans;
while(tm.empty()==0)
{
ans+=tm.top();
tm.pop();
}
int sz=ans.size();
if(sz>1&&ans[sz-1]=='/')
{
return ans.substr(0,sz-1);
}
return ans;
}
};