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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (path.empty()) {
return "";
}
deque<string> dq;
char ch = ' ', pre = ' ';
const char* p = path.c_str();
string sub_path;
ch = *p;
if (ch == '/') {
sub_path.push_back(ch);
pre = ch;
dq.push_back(sub_path);
sub_path.clear();
}
++p;
while (ch = *p) {
if (ch == '/' && pre != '/') {
if (sub_path == "\.") {
;
} else if (sub_path == "\.\.") {
if (dq.back() != "/") {
dq.pop_back();
}
} else {
sub_path.push_back(ch);
pre = ch;
dq.push_back(sub_path);
}
pre = ch;
sub_path.clear();
++p;
} else if (ch == '/' && pre == '/') {
++p;
} else {
sub_path.push_back(ch);
pre = ch;
++p;
}
}
if (sub_path != "\." && sub_path != "\.\.") {
dq.push_back(sub_path);
} else if (sub_path == "\.\.") {
if (dq.back() != "/") {
dq.pop_back();
}
}
string result;
while (!dq.empty()) {
result.append(dq.front());
dq.pop_front();
}
if (result.size() > 1 && *result.rbegin() == '/') {
return string(result.c_str(), result.size() -1);
} else {
return result;
}
}
};