-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path071.Simplify_Path.cpp
More file actions
50 lines (41 loc) · 1.22 KB
/
071.Simplify_Path.cpp
File metadata and controls
50 lines (41 loc) · 1.22 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
#include <list>
#include <string>
#include <iostream>
using namespace std;
class Solution {
public:
string simplifyPath(string path) {
if (path.empty() || path == "/") return "/";
list<string> list;
int current_pos = 0;
int next_pos = 0;
do {
next_pos = path.find_first_of('/', current_pos + 1);
if (next_pos == string::npos) next_pos = path.size();
string s = path.substr(current_pos + 1, next_pos - current_pos - 1);
if (s.empty() || s == ".") {
//do nothing
} else if (s == "..") {
//cd ..
if (!list.empty()) list.pop_back();
} else {
//part of the path
list.push_back(s);
}
current_pos = next_pos;
} while (next_pos != path.size());
if (list.empty()) return "/";
string result;
while (!list.empty()) {
result.append("/");
result.append(list.front());
list.pop_front();
}
return result;
}
};
int main(int argc, char **argv) {
Solution solution;
cout << solution.simplifyPath("/../") << endl;
return 0;
}