Simplify Path
Given an absolute path for a file (Unix-style), simplify it.
For example,
path =
path =
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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
//parse string
deque<string> layer;
for(int start=0; start < path.length();){
if (path[start] == '/'){
++start;
continue;
}
int end = path.find('/',start);
if (end == string::npos) end = path.length()-1;
string line(path.substr(start, end-start+1));
start = end + 1;
if (line.compare("./")==0 || line.compare(".") == 0) continue;
else if (line.compare("../")==0 || line.compare("..")==0){
if (layer.empty()) continue;
else layer.pop_back();
}else layer.push_back(line);
}
string r("/");
while(!layer.empty()){
r += layer.front();
layer.pop_front();
}
if (r.length() > 1 && *r.rbegin()=='/') r.resize(r.length()-1);
return r;
}
};
No comments:
Post a Comment