1
// Please upvote if it helps
2
class Solution {
3
public:
4
string simplifyPath(string path) {
5
stack<string> st;
6
string res;
7

8
for (int i = 0; i < path.size(); ++i) {
9
if (path[i] == '/') continue;
10
string temp;
11
// iterate till we doesn't traverse the whole string and doesn't encounter
12
// the last /
13
while (i < path.size() && path[i] != '/') {
14
// add path to temp string
15
temp += path[i];
16
++i;
17
}
18
if (temp == ".") continue;
19
// pop the top element from stack if exists
20
else if (temp == "..") {
21
if (!st.empty()) st.pop();
22
} else
23
// push the directory file name to stack
24
st.push(temp);
25
}
26

27
// adding all the stack elements to res
28
while (!st.empty()) {
29
res = "/" + st.top() + res;
30
st.pop();
31
}
32

33
// if no directory or file is present
34
if (res.size() == 0) return "/";
35

36
return res;
37
}
38
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0