-
-
Notifications
You must be signed in to change notification settings - Fork 291
Expand file tree
/
Copy path71.java
More file actions
116 lines (113 loc) · 3.52 KB
/
71.java
File metadata and controls
116 lines (113 loc) · 3.52 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
__________________________________________________________________________________________________
sample 1 ms submission
class Solution {
public String simplifyPath(String path) {
if (path.length() == 0)
return path;
char[] str = new char[path.length()];
int[] dir = new int[path.length()];
int di = 0, si = 0;
int point_num = 0, len = path.length();
for (int i = 0; i < len; ++i)
{
char c = path.charAt(i);
switch(c)
{
case '/':
if (si == 0)
{
str[si++] = c;
dir[di++] = 0;
}
else if (str[si-1] == '/')
;
else if (str[si-1] == '.')
{
if (point_num == 1)
si--;
else if (point_num == 2)
{
if (di == 1)
{
si = dir[0] + 1;
di++;
}
else if (str[dir[di-2]] == '/')
{
si = dir[di-2] + 1;
}
else
{
si = dir[di-2] + 2;
}
di--;
}
point_num = 0;
}
else
{
dir[di++] = si - 1;
str[si++] = c;
}
break;
case '.':
str[si++] = c;
point_num++;
break;
default:
point_num = 0;
str[si++] = c;
}
}
if (point_num == 1)
si--;
else if (point_num == 2)
{
if (di == 1)
{
si = dir[0] + 1;
}
else if (str[dir[di-2]] == '/')
{
si = dir[di-2] + 1;
}
else
{
si = dir[di-2] + 2;
}
}
if (str[si - 1] == '/' && si != 1)
si--;
return new String(str, 0, si);
}
}
__________________________________________________________________________________________________
sample 35628 kb submission
class Solution {
public String simplifyPath(String path) {
Stack<String> stack = new Stack<String>();
String[] str = path.split("/");
for (String ss: str) {
String s = ss.trim();
if (s.length() > 0) {
if (s.equals("..")) {
if (!stack.isEmpty()) {
stack.pop();
}
} else if (!s.equals(".")){
stack.push(s);
}
}
}
StringBuilder strbld = new StringBuilder();
while (!stack.isEmpty()) {
strbld.insert(0, stack.pop());
strbld.insert(0, "/");
}
if (strbld.length() == 0) {
return "/";
}
return strbld.toString();
}
}
__________________________________________________________________________________________________