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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<string> dirVector;
char *pChar = &path[0];
while (*pChar != '\0')
{
if (*pChar == '/')
{
while (*pChar == '/')
pChar++;
if (*pChar != '\0')
{
string curDir;
while (*pChar != '/' && *pChar != '\0')
{
curDir += *pChar++;
}
if (curDir.compare(".") == 0)
{
continue;
}
else if (curDir.compare("..") == 0)
{
if (!dirVector.empty())
dirVector.pop_back();
}
else
{
dirVector.push_back(curDir);
}
}
}
}
string retString("/");
int dirSize = dirVector.size();
for (int i = 0; i < dirSize; i++)
{
retString += dirVector[i];
if (i != dirSize-1)
retString += "/";
}
return retString;
}
};