-
Notifications
You must be signed in to change notification settings - Fork 2
/
simplify_path.cc
73 lines (69 loc) · 1.79 KB
/
simplify_path.cc
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
// Given an absolute path for a file (Unix-style), simplify it.
//
// For example,
// path = "/home/", => "/home"
// path = "/a/./b/../../c/", => "/c"
/**
* I will definately simplify this solution later...
*/
class Solution {
public:
string simplifyPath(string path) {
stack<string> st;
if (path[0] == '/') {
st.push(string("/"));
}
int i = 0;
int j = 0;
string p;
string parent("..");
string current(".");
string root("/");
string empty("");
while (i != path.size()) {
while (i != path.size() && path[i] == '/') {
i++;
}
j = i;
while (j != path.size() && path[j] != '/') {
j++;
}
p = path.substr(i, j - i);
if (p == empty) {
break;
}
else if (p == current) {
if (st.empty()) {
st.push(p);
}
}
else if (p == parent) {
if (st.top() == current) {
st.pop();
st.push(p);
}
else {
if (st.top() != root) {
st.pop();
}
}
}
else {
st.push(p);
}
i = j;
}
string result("");
if (st.top() == root) {
return root;
}
while (!st.empty()) {
result = string("/") + st.top() + result;
st.pop();
}
if (result[0] == '/' && result[1] == '/') {
return result.substr(2, result.size() - 2);
}
return result.substr(1, result.size() - 1);
}
};