Skip to content

Commit 673bbdb

Browse files
Create simplify_directory_path.cpp
1 parent 82331a0 commit 673bbdb

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
// Given a string A representing an absolute path for a file (Unix-style).
2+
// Return the string A after simplifying the absolute path.
3+
// Note:
4+
// Absolute path always begin with ( root directory ).
5+
// Path will not have whitespace characters.
6+
7+
#include <bits/stdc++.h>
8+
using namespace std;
9+
10+
string simplifyPath(string A)
11+
{
12+
13+
A+="/";
14+
string loc="", ans="";
15+
vector<string> v;
16+
stack<string>s;
17+
int n= A.length();
18+
19+
// spliting the path with / as delimeter
20+
for(int i=0; i<n; i++)
21+
{
22+
if(A[i]=='/')
23+
{
24+
if(loc!="" )
25+
v.push_back(loc);
26+
loc="";
27+
}
28+
else
29+
{
30+
loc+= A[i];
31+
}
32+
}
33+
34+
//simplifying the path ans storing in stack
35+
for(auto x: v)
36+
{
37+
if(x!="." && x!="..")
38+
s.push(x);
39+
else if( x==".." && s.size()!=0)
40+
s.pop();
41+
42+
}
43+
if(s.empty())
44+
ans="/";
45+
46+
//since the path is reversed in stack s, we are reversing it again using fs stack
47+
stack< string > fs;
48+
while(!s.empty())
49+
{
50+
fs.push(s.top());
51+
s.pop();
52+
}
53+
54+
//printing the simplified path
55+
while (!fs.empty() )
56+
{
57+
ans+="/"+fs.top();
58+
fs.pop();
59+
}
60+
return ans;
61+
}
62+
63+
64+
int main()
65+
{
66+
string str;
67+
cin>>str;
68+
cout<<simplifyPath(str);
69+
return 0;
70+
71+
}

0 commit comments

Comments
 (0)