-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
31 lines (29 loc) · 1018 Bytes
/
Solution.java
File metadata and controls
31 lines (29 loc) · 1018 Bytes
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
package leetcode._71_;
import java.util.Deque;
import java.util.LinkedList;
class Solution {
public String simplifyPath(String path) {
String[] split = path.split("/");
Deque<String> strings = new LinkedList<>(); // 使用双端队列
for (String s : split) {
if (!s.equals("") && !s.equals(".")) {
if (s.equals("..")) {
if (!strings.isEmpty()) {
strings.pop(); // 双端队列可以用作栈,返回上一层目录
}
} else {
strings.push(s); // 双端队列压栈写入头部元素
}
}
}
if (strings.isEmpty()) {
return "/";
}
StringBuilder stringBuilder = new StringBuilder();
while (!strings.isEmpty()) {
stringBuilder.append("/");
stringBuilder.append(strings.pollLast()); // 出尾部元素
}
return stringBuilder.toString();
}
}