-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFeb_P5_SimplifyPath.cpp
46 lines (37 loc) · 1.32 KB
/
Feb_P5_SimplifyPath.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) {
int n=path.length();
stack<string>s;
if(path[n-1]!='/') // so that initially path always ends with '/'
path+="/", ++n;
int i=1; // since path always starts from '/'
string ans="";
string temp="";
while(i<n){
if(path[i]=='/'){ // check only if we encounter '/'
if(temp=="" || temp=="."){
// ignore
}
else if(temp==".."){
if(!s.empty()) s.pop(); // pop the top element from stack if exists
}
else{
s.push(temp); //push the directory or file name to stack
}
temp=""; // reset temp
}
else{
temp.push_back(path[i]); // else append to temp
}
++i; // increment index
}
while(!s.empty()){ // add all the stack elements
ans="/"+s.top()+ans;
s.pop();
}
if(ans.length()==0) // if no directory or file is present
ans="/"; // minimum root directory must be present in ans
return ans;
}
};