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"
.
------------------------- thinking ------------------------
edge cases "/." "///" "/"
https://oj.leetcode.com/discuss/24939/c-10-lines-solution
--------------------------- codes ----------------------------
class Solution {
public:
string simplifyPath(string path) {
if (path.size() == 1) {
return path;
}
vector<string> tmp_path;
int start = 0;
int end = 1;
while (start < path.size() && end < path.size()) {
if (path[end] == '/') {
string sub = path.substr(start + 1, end - start - 1);
if (sub.size() > 0) {
if (sub.compare("..") == 0) {
if (tmp_path.size() > 0) {
tmp_path.pop_back();
}
} else if (sub.compare(".") != 0) {
tmp_path.push_back(sub);
}
}
start = end;
}
end++;
}
if (start < path.size() - 1) {
string sub = path.substr(start+1);
if (sub.compare("..") == 0) {
if (tmp_path.size() > 0) {
tmp_path.pop_back();
}
} else if (sub.compare(".") != 0) {
tmp_path.push_back(sub);
}
}
string out;
if (tmp_path.size() == 0) {
return "/";
}
for (int i = 0; i < tmp_path.size(); i++) {
out += "/";
out += tmp_path[i];
}
return out;
}
};
No comments:
Post a Comment