Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
Corner
Cases:
- Did you consider the case where path =
"/../"
?
In this case, you should return"/"
. - Another corner case is the path might contain multiple slashes
'/'
together, such as"/home//foo/"
.
In this case, you should ignore redundant slashes and return"/home/foo"
.
题意
简化unix风格的绝对路径
题解
有几种情况需要处理 一是多个/只当1个/处理
二是..表示进入父目录
用一个栈结构存储目录路径的每个文件夹,遇到..则出栈
class Solution {
public:
string simplifyPath(string path) {
stack<string> file;
for(int i=0;i<path.size();)
{
while(path[i]=='/'&&i<path.size())
i++;
string temp;
while(path[i]!='/'&&i<path.size())
temp+=path[i++];
if(temp==".."&&!file.empty())
file.pop();
if(temp!="."&&temp!=".."&&temp!="")
file.push(temp);
}
string res;
if(file.empty())
res="/";
while(!file.empty())
{
res=file.top()+res;
res='/'+res;
file.pop();
}
return res;
}
};