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"
.
思路:
用一个栈来实现,对特殊情况进行判断
代码:
1 string simplifyPath(string path) { 2 // IMPORTANT: Please reset any member data you declared, as 3 // the same Solution instance will be reused for each test case. 4 stackStack; 5 while(true){ 6 if(path == "/") 7 break; 8 int index = path.find('/', 1); 9 string tmp;10 if(index == -1){11 tmp = path.substr(1);12 path = "/";13 }14 else{15 tmp = path.substr(1, index-1);16 path = path.substr(index);17 }18 if(tmp == "")19 continue;20 else if(tmp == ".."){21 if(!Stack.empty())22 Stack.pop();23 else24 continue;25 }26 else if(tmp != ".") 27 Stack.push(tmp);28 }29 string result = "";30 if(Stack.empty())31 return "/";32 while(!Stack.empty()){33 result = "/" + Stack.top() + result;34 Stack.pop();35 }36 return result;37 }