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> s;
string ans = "";
int i = 0;
while(i < path.length())
{
while(i<path.length() && path[i] == '/')
i++;
string name = "";
while(i<path.length() && path[i] != '/')
name += path[i++];
if(name == ".." && !s.empty())
s.pop();
else if(name != "" && name != "." && name != "..")
s.push(name);
}
if(s.empty())
ans = "/";
else
{
while(!s.empty())
{
ans = "/" + s.top() + ans;
s.pop();
}
}
return ans;
}
};