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) {
vector<string> re;
string s = "";
for(int i = 0; i < path.length(); i++){
if(s == ".." && path[i] == '/'){
if(re.size() != 0)
re.pop_back();
s.clear();
}
else if(path[i] != '/'){
s += path[i];
}
else if(s.length() != 0){
if(s != "."){
re.push_back(s);
}
s.clear();
}
else
continue;
}
if(s == ".."){
if(re.size() != 0)
re.pop_back();
}
else if(s.length() != 0 && s != "."){
re.push_back(s);
}
string ans = "";
for(int i = 0; i < re.size(); i++){
ans += "/";
ans += re[i];
}
return (ans.length() == 0) ? "/" : ans;
}
};