-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy path20120403 Simplify Path.cpp
More file actions
42 lines (40 loc) · 1.27 KB
/
20120403 Simplify Path.cpp
File metadata and controls
42 lines (40 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/*
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
click to show corner cases.
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) {
//cout << "here" << endl;
vector<string> resVec;
string ans = "";
int pos = 0, rpos;
while ((rpos = path.find("/", pos+1)) != string::npos) {
resVec.push_back(path.substr(pos, rpos-pos));
cal(resVec);
pos = rpos;
}
resVec.push_back(path.substr(pos));
cal(resVec);
if (resVec.size() == 0) resVec.push_back("/");
for (auto &s: resVec) ans.append(s);
return ans;
}
void cal(vector<string> &vec) {
string s = vec[vec.size() - 1];
if (s == "/" || s == "/.") {
vec.pop_back();
} else if (s == "/..") {
vec.pop_back();
if (vec.size()) vec.pop_back();
}
}
};