Simplify Path
这个题是给出一个字符串的相对路径,让我们返回绝对路径,让我们在Linux下自己去动手操作确实不难,可是用程序做起来的话确实比较麻烦。
我的解题思路是找好‘/’和‘.’之间的关系,找好他们之间的组合关系后这个题就容易一些。在路径中‘.’和‘/’的组合正常的可能只有‘.’和‘..’两种。‘/’是起修饰作用的,说明当前目录下可能还存在目录。
既然我们要写这个题的话,那么肯定会出现各种组合的情况,其实我们只要处理好两种正常的情况就差不多了,其他的情况稍微注意一下就可以了。下面就先看看我的代码吧!
class Solution
{
public:
string simplifyPath(string path)
{
stack<char> S;
string aPath = ""; //返回串
if (path.size() == 0)
{
return aPath;
}
int Status = 0; //保存当前‘.’的个数
int i = 0;
int sz = path.size();
char visited = 0; //最近访问的符号
int Dir = 0; //当前目录个数
while (i<sz)
{
if (path[i] == '.')
{ //统计连续‘.’的数目
++Status;
while (++i < sz && path[i] == '.')
++Status;
visited = '.';
}
if (i < sz && path[i] == '/')
{
if (Status == 0)
{
if (visited != '/' && S.size()!=1) //防止连续‘/’或者‘/’复制错误 /../ -> /
{
S.push('/');
visited = '/';
}
}
else if (Status == 1) //当前目录
{
visited = '/';
Status = 0;
}
else if (Status == 2)
{
if (!S.empty() && Dir > 0) // 存在目录则返回上级目录
{
S.pop();
while (!S.empty() && S.top() != '/')
{
S.pop();
}
--Dir;
visited = '/';
}
else if (S.empty())
{
S.push('/');
visited = '/';
}
Status = 0;
}
else
{
while (Status--) //目录之前的‘.’
S.push('.');
S.push('/');
visited = '/';
Status = 0;
}
}
else
{
if (i < sz)
{
while (Status--)
S.push('.');
Status = 0;
while (i < sz && path[i] != '/' && path[i] != '.') //完整目录
{
S.push(path[i]);
visited = path[i];
++i;
}
++Dir;
if (path[i] == '/' || path[i] == '.') //往回退一个位置
--i;
visited = path[i];
}
}
++i;
}
if (Status > 0)
{
if (Status == 1)
{
//do nothing
}
else if (Status == 2)
{ // 2
if (!S.empty() && Dir > 0) //末尾可能出现上级目录 /a/.. -> /
{
S.pop();
while (!S.empty() && S.top() != '/')
{
visited = S.top();
S.pop();
}
--Dir;
}
}
else
{ // > 2
while (Status--)
S.push('.');
Status = 0;
}
}
while (!S.empty()) //将栈里面的内容取出来
{
char ch = S.top();
string tmp = "";
tmp += ch;
aPath = tmp + aPath;
S.pop();
}
if (aPath.size() > 1)
{
int end = aPath.size() - 1;
while (end > 0 && aPath[end--] == '/') //末尾位置的‘/’应该去掉
aPath.pop_back();
}
return aPath;
}
};
请注意仔细看看注释部分,因为有些情况的结果可能跟我们预想的不他一样,所以只能按照题目给的方向来解决了,下面是运行结果:
(最后解析一下为什么好久没有写博客了,因为我去实习了,所以没有时间来写博客了,今天是完成了任务以后抽出时间来写的,不过写完了也到半夜了,最近可能不会每天都写博客了,但是应该每周都会写一些吧)