Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
class Solution {
public:
string simplifyPath(string path) {
stack<string> q;
string name;
name.clear();
string ret = "";
int len = path.length();
if(len == 0)
{
return ret;
}
int i;
for(i = 0;i < len;i ++)
{
if(path[i] == '/')
{
if(!name.empty())
{
if(name == "..")
{
if(!q.empty())
{
q.pop();
}
}
else if(!(name[0] == '.' && name.length() == 1))
{
q.push(name);
}
}
name.clear();
}
else
{
name += path[i];
}
}
if(!name.empty()) {
if(name == "..")
{
if(!q.empty())
{
q.pop();
}
}
else if(!(name[0] == '.' && name.length() == 1))
{
q.push(name);
}
}
if(q.empty())
{
return "/";
}
ret = '/' + q.top();
q.pop();
while(!q.empty())
{
ret = '/' + q.top()+ ret;
q.pop();
}
return ret;
}
};