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"
.
思路:当碰到..回到上层路径,.还是当前路径,由此可知用栈即可实现。
class Solution { public: string simplifyPath(string path) { string simple = ""; stack<string> S; stack<string> S2; if(path.empty()) { return simple; } int i, len = path.length(),j; string str = ""; for(i=1; i<len; ++i) { if (path[i] == '/' || i==len-1) { if (i==len-1 && path[i]!='/') { str += path[i]; } if (!str.empty()) { if (str == "..") { str.clear(); if (!S.empty()) { S.pop(); } continue; } if (str == ".") { str.clear(); continue; } S.push(str); str.clear(); } } else { str += path[i]; } } if (S.empty()) { return "/"; } while(!S.empty()) { S2.push(S.top()); S.pop(); } while(!S2.empty()) { simple += '/'; simple += S2.top(); S2.pop(); } return simple; } };