Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
string simplifyPath(string path)
{
if(path.length() == 0 || path[0] != '/')
{
return "";
}
string result;
vector<string> wordPath;
int i = 0;
int size = (int)path.size();
int end = 0;
while(i < size)
{
end = i + 1;
while(end < size && path[end] != '/')
{
end++;
}
string tmpWord = path.substr(i + 1, end - i - 1);
if(tmpWord.length() > 0)
{
if(tmpWord == "..")
{
if(!wordPath.empty())
{
wordPath.pop_back();
}
}
else if(tmpWord != ".")
{
wordPath.push_back(tmpWord);
}
}
i = end;
}
if(wordPath.empty())
{
return "/";
}
else
{
for(int i = 0; i < (int)wordPath.size(); i++)
{
result.append("/");
result.append(wordPath[i]);
}
}
return result;
}