今天做了一道比较有意思的题目,处理UNIX路径的字符串操作。
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
路径中/表示根,.表示当前目录,..表示父级目录
使用栈保存路径
string simplifyPath(string path)
{
string result = "";
vector<string> pathStack;
for(auto i = path.begin(); i != path.end();)
{
i++;
auto j = find(i,path.end(),'/');
string dir = string(i,j);
if(!dir.empty() && dir != ".")
{
//parent dir
if(dir == "..")
{
if(!pathStack.empty())
{
pathStack.pop_back();
}
}
//dir
else
{
pathStack.push_back(dir);
}
}
//update pos
i = j;
}
if(pathStack.empty())
{
return "/";
}
else
{
for(auto dir : pathStack)
{
result += "/";
result += dir;
}
return result;
}
}