Given an absolute path for a file (Unix-style), simplify it.
For example,path =
"/home/"
, => "/home"
path = "/a/./b/../../c/"
, =>
"/c"
对unix-style的path进行了下了解,.可以忽略不计,..返回上一级目录,因此我们就需要一个结构来存储上一级目录,也就是后进先进,当然理所当然的就是栈结构。然后需要注意的是,栈在为空的时候不能调用pop操作,以及最后输出结果时,路径的顺序不要弄反了 - -
代码如下:
class Solution {
public:
string simplifyPath(string path) {
stack<string> stack;
stringstream ss(path);
string tmp;
while(getline(ss,tmp,'/'))
{
if(tmp == "." || tmp == "") continue;
else if(tmp == ".." && !stack.empty())
stack.pop();
else if(tmp != "..")
stack.push(tmp);
}
string result;
while(!stack.empty())
{
result = "/"+stack.top() + result;
stack.pop();
}
return result.empty()?"/":result;
}
};