-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0071-simplify-path.cpp
More file actions
45 lines (42 loc) · 1.37 KB
/
0071-simplify-path.cpp
File metadata and controls
45 lines (42 loc) · 1.37 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
43
44
45
class Solution {
public:
string simplifyPath(string path) {
string last = "";
vector<string> dirs;
for (int i = 0; i < path.size(); ) {
char ch = path[i];
if (ch == '/' && ((i + 1 < path.size() && path[i + 1] == '/') || (i == path.size() - 1))) {
i = i + 1;
} else if (ch == '/' && ((i + 2 < path.size() && path[i + 1] == '.' && path[i + 2] == '/') || (i + 1 == path.size() - 1 && path[i + 1] == '.'))) {
i = i + 2;
} else {
if (ch == '/') {
if (last != "") {
if (last == "..") {
if (!dirs.empty()) dirs.pop_back();
} else {
dirs.push_back(last);
}
}
last = "";
} else {
last += ch;
}
i = i + 1;
}
}
if (last != "") {
if (last == "..") {
if (!dirs.empty()) dirs.pop_back();
} else {
dirs.push_back(last);
}
}
string ans = "";
for (int i = 0; i < dirs.size(); ++i) {
ans += '/' + dirs[i];
}
if (ans == "") ans = "/";
return ans;
}
};