题目
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
,
=> "/home"
path = "/a/./b/../../c/"
,
=> "/c"
-
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"
.
思路
特殊情况的考虑比较麻烦,细心一点就好了。
用栈来操作。
会出现的特殊情况:
"/" ---------------> "/"
"///" ------------------->"/"
"/../" ------------------->"/"
"/.hidden" ---------------->"/.hidden"
"/."------------------------> "/"
"/.." ---------------------->"/"
"/.hidden/" ------------------------->"/.hidden"
"/a/./b/../../c/" ------------------------>"/c"
代码吐下:
class Solution {
public:
string simplifyPath(string path) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
stack<string> mypath;
string str = "";
int len = path.length();
if(len<=1)
return path;
for(int i=0;i<len;i++){
if(path[i]=='/'){
if(i>0 && str.length()>0)
{
if(str==".."){
if(!mypath.empty()){
mypath.pop();
}
}else if(str!="."){
mypath.push(str);
}
}
str = "";
}
else
str+=path[i];
}
if(str==".."){
if(!mypath.empty()){
mypath.pop();
}
}else if(str!="." && str!=""){
mypath.push(str);
}
str = "";
if(mypath.empty())
return "/";
while(!mypath.empty())
{
str = mypath.top()+str;
mypath.pop();
str.insert(str.begin(),1,'/');
}
return str;
}
};