-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path71.Simplify-Path.java
45 lines (39 loc) · 1.06 KB
/
71.Simplify-Path.java
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
// https://leetcode.com/problems/simplify-path/
//
// algorithms
// Medium (28.70%)
// Total Accepted: 149,468
// Total Submissions: 520,771
class Solution {
public String simplifyPath(String path) {
if (path.equals("")) {
return "";
}
LinkedList<String> stack = new LinkedList<>();
String[] arr = path.split("/+");
for (String s : arr) {
if (!s.equals("")) {
switch (s) {
case ".":
break;
case "..":
if (!stack.isEmpty()) {
stack.pollLast();
}
break;
default:
stack.offer(s);
break;
}
}
}
StringBuilder sb = new StringBuilder();
sb.append("/");
String last = stack.isEmpty() ? "" : stack.pollLast();
for (String s : stack) {
sb.append(s).append("/");
}
sb.append(last);
return sb.toString();
}
}