#include <iostream>
#include <vector>
#include <stack>
using namespace std;
string SimplifyPath(string path)
{
path.push_back('/');
stack<size_t> iStack;
size_t pos = 0;
iStack.push(pos);
for (int i = 1; i < path.size(); ++i)
{
char c = path[i];
if (c != '/')
{
path[++pos] =c;
continue;
}
if(path[i-1] == '/') continue;
path[++pos] = c;
int dir = iStack.top();
if (path[dir+1] == '.')
switch (path[dir+2])
{
case '/': pos = dir; break;
case '.':
if (path[dir+3] != '/')
iStack.push(pos);
else
{
if(iStack.size() > 1) iStack.pop();
pos = iStack.top();
}
break;
default:
iStack.push(pos);
break;
}
else
iStack.push(pos);
}
if (pos == 0)pos = pos+1;
path.erase(pos);
return path;
}
string SimplifyPath2(string path)
{
vector<string> pathStack;
string directory;
path.push_back('/');
for (int i = 0; i < path.size(); ++i)
{
char c = path[i];
if (c != '/')
{
directory.push_back(c);
continue;
}
if (directory.size() <=0) continue;
if (directory[0] == '.')
{
if (directory.size() > 1)
{
if(directory[1] == '.')
{
if (directory.size() > 2)
pathStack.push_back(directory);
else
if (pathStack.size() > 0)
pathStack.pop_back();
}
else
pathStack.push_back(directory);
}
}
else
pathStack.push_back(directory);
directory.clear();
}
path.clear();
for (int i = 0; i < pathStack.size(); ++i)
path += '/' + pathStack[i];
if (path.size() <=0 )path = "/";
return path;
}
int main(int argc, char** argv)
{
string s = "/home/../..";
cout << s << " => " << SimplifyPath(s) << endl;
s = "/a/./.b/../../c/";
cout << s << " => " << SimplifyPath2(s) << endl;
s = "/home/of/foo/../../bar/../../is/./here/.";
cout << s << " => " << SimplifyPath2(s) << endl;
return 0;
}