Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
Corner Cases:
Solution:
- 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"
.
Code:
<span style="font-size:14px;">class Solution {
public:
string simplifyPath(string path) {
path += "/";
int length = path.size();
stack<string> stk;
string name;
for (int i = 0; i < length; i++) {
if (path[i] == '/') {
if (name == "." || name == "") {
} else if (name == "..") {
if (!stk.empty()) stk.pop();
} else stk.push(name);
name = "";
} else
name += path[i];
}
string result;
while (!stk.empty()) {
result = "/" + stk.top() + result;
stk.pop();
}
if (result == "") return "/";
return result;
}
};</span>