-
Notifications
You must be signed in to change notification settings - Fork 28
/
Simplify_Path.cpp
36 lines (35 loc) · 1 KB
/
Simplify_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
class Solution {
public:
string simplifyPath(string path) {
string result = "/";
deque<string> dQ;
for(int i = 0; i < path.length(); ) {
int pos = path.find('/', i);
string dir;
if(pos == string::npos) {
pos = path.length();
}
dir = path.substr(i, pos - i);
if(!dir.empty()) {
if(dir == ".") {
// nothing
} else if(dir == "..") {
if(!dQ.empty()) {
dQ.pop_back();
}
} else {
dQ.push_back(dir);
}
}
// skip all redundant slaces
for( ;pos < path.length() and path[pos] == '/'; ++pos);
i = pos;
}
while(!dQ.empty()) {
result += dQ.front();
dQ.pop_front();
if(!dQ.empty()) result += '/';
}
return result;
}
};