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) {
int i = 0;
stack<string> s;
stack<string> ans;
string temp = "";
int flag = 0;
for(i = 0;i<path.length();i++)
{
if(path[i] == '/' && flag == 0)//开始一个文件夹
{
temp = "";
flag = 1;
}
else if(path[i] == '/' && flag == 2)//结束一个文件夹
{
if(temp == ".")
{
flag = 0;
i--;
continue;
}
else if(temp == "..")
{
if(!s.empty())
{
s.pop();
}
}
else
{
s.push(temp);
}
flag = 0;
i--;
}
else if((flag == 1 || flag == 2)&& path[i] != '/' )//文件夹的名字
{
temp = temp + path[i];
flag = 2;
}
}
/*最后一个文件夹*/
if(flag == 2)
{
if(temp != ".")
{
if(temp == "..")
{
if(!s.empty())
{
s.pop();
}
}
else
s.push(temp);
}
}
while(!s.empty())/*目录正序输出*/
{
ans.push(s.top());
s.pop();
}
string direction = "/";//最终简化目录
while(ans.size()!=0)
{
direction = direction + ans.top();
if(ans.size() != 1)
direction = direction + "/";
ans.pop();
}
return direction;
}
};