-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0071. Simplify Path.cpp
More file actions
56 lines (55 loc) · 1.68 KB
/
0071. Simplify Path.cpp
File metadata and controls
56 lines (55 loc) · 1.68 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
46
47
48
49
50
51
52
53
54
55
56
class Solution {
public:
string simplifyPath(string path) {
// parse input into stack
stack<string> stk;
string dir = "";
for (int i = 0; i < path.size(); i++) {
// skip consecutive slashes
if (path[i] == '/') {
while (i < path.size() && path[i] == '/')
i++;
i--;
}
// otherwise get directory or move
else {
if (path[i] != '.' && path[i] != '/') {
dir = "";
while (i < path.size() && path[i] != '.' && path[i] != '/') {
dir += path[i];
i++;
}
stk.push(dir);
i--;
} else {
dir = "";
while (i < path.size() && path[i] != '/') {
dir += path[i];
i++;
}
i--;
if (dir.size() == 2) {
if (!stk.empty()) {
stk.pop();
}
} else if (dir.size() > 2)
stk.push(dir);
// brackets cost me an hour...
}
}
}
// reverse the stack, concatenate answer, and return
string ans = "";
stack<string> temp;
while (!stk.empty()) {
temp.push(stk.top());
stk.pop();
}
while (!temp.empty()) {
ans += "/";
ans += temp.top();
temp.pop();
}
return (ans == "") ? "/" : ans;
}
};