-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path71_Simplify_Path.cpp
More file actions
53 lines (37 loc) · 1.15 KB
/
Copy path71_Simplify_Path.cpp
File metadata and controls
53 lines (37 loc) · 1.15 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
class Solution {
public:
string simplifyPath(string path) {
stack<string>s;
int idx = 0;
auto get_next_item = [&](){
idx++;
string next_dir = "";
while(idx < path.size() && path[idx] != '/'){
next_dir+=path[idx++];
}
while(idx < path.size() - 1 && path[idx] == '/' && path[idx + 1] == '/')idx++;
return next_dir;
};
bool flag = false;
while(!flag){
string next_dir = get_next_item();
if(next_dir == "" && idx >= path.size())break;
if(next_dir == ".")continue;
if(next_dir == ".."){
if(!s.empty())s.pop();
}else if(next_dir != "") s.push(next_dir);
}
vector<string>aux;
while(!s.empty()){
aux.push_back(s.top());
s.pop();
}
reverse(aux.begin(),aux.end());
string ans = "/";
for(int i = 0;i<aux.size();i++){
ans+=aux[i];
if(i < aux.size() - 1)ans+="/";
}
return ans;
}
};