-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathSimplify_Path.cpp
More file actions
90 lines (69 loc) · 1.39 KB
/
Copy pathSimplify_Path.cpp
File metadata and controls
90 lines (69 loc) · 1.39 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/*
Simplify Path
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
"/home/foo/../bar" "/bar" "/home/bar"
"/home/foo/./.././bar" "/home/foo/bar" "/home/bar"
*/
#include <string>
#include <iostream>
using namespace std;
class Solution {
public:
string simplifyPath(string path) {
string p;
//remove duplicate slash
int slash = 0;
for (int i = 0; i < path.size(); i++) {
if (!slash || path[i] != '/')
p += path[i];
slash = (path[i] == '/');
}
//remove '/.'
if (p[p.size()-1] != '/')
p += '/';
while (1) {
int dot = p.find("/./");
if (dot == -1) {
break;
}
if (dot + 2 < p.size()) {
p = p.substr(0, dot) + p.substr(dot + 2);
} else {
p = p.substr(0, dot);
}
}
// resolve "/.."
while (1) {
int dotdot = p.find("/..");
if (dotdot == -1) {
break;
}
int end = dotdot - 1;
end = max(0, end);
while (end > 0) {
if (p[end] == '/') {
break;
}
end--;
}
if (dotdot + 3 < p.size())
p = p.substr(0, end) + p.substr(dotdot + 3);
else
p = p.substr(0, end);
}
if (p.size() == 0)
return "/";
if (p.size() > 1 && p[p.size()-1] == '/')
return p.substr(0, p.size() - 1);
return p;
}
};
int main(int argc, char *argv[])
{
Solution c;
cout << c.simplifyPath("/home/foo/../bar") << endl;
return 0;
}