forked from PRAN20/Top-Interview-Questions-LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Simply_path.cpp
46 lines (41 loc) · 1.12 KB
/
Simply_path.cpp
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
class Solution {
public:
string simplifyPath(string path) {
stack<string> st;
string res;
for(int i = 0; i<path.size(); ++i)
{
if(path[i] == '/')
continue;
string temp;
// iterate till we doesn't traverse the whole string and doesn't encounter the last /
while(i < path.size() && path[i] != '/')
{
// add path to temp string
temp += path[i];
++i;
}
if(temp == ".")
continue;
// pop the top element from stack if exists
else if(temp == "..")
{
if(!st.empty())
st.pop();
}
else
// push the directory file name to stack
st.push(temp);
}
// adding all the stack elements to res
while(!st.empty())
{
res = "/" + st.top() + res;
st.pop();
}
// if no directory or file is present
if(res.size() == 0)
return "/";
return res;
}
};