-
Notifications
You must be signed in to change notification settings - Fork 180
Expand file tree
/
Copy pathq071_SimplifyPath.java
More file actions
38 lines (33 loc) · 1.06 KB
/
q071_SimplifyPath.java
File metadata and controls
38 lines (33 loc) · 1.06 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
package leetcode_algorithm;
import java.util.*;
/**
* Given an absolute path for a file (Unix-style), simplify it.
* <p>
* For example,
* path = "/home/", => "/home"
* path = "/a/./b/../../c/", => "/c"
*/
public class q071_SimplifyPath {
public static void main(String[] args) {
System.out.println(new q071_SimplifyPath().simifyPath("../"));
System.out.println(new q071_SimplifyPath().simifyPath("/home/"));
System.out.println(new q071_SimplifyPath().simifyPath("/a/./b/../../c/"));
}
/**
* ½â·¨1(ÍÆ¼ö½â·¨)
*
* @param path
* @return
*/
public String simifyPath(String path) {
Deque<String> stack = new LinkedList<>();
Set<String> skip = new HashSet<>(Arrays.asList("..", ".", ""));
for (String dir : path.split("/")) {
if (dir.equals("..") && !stack.isEmpty()) stack.pop();
else if (!skip.contains(dir)) stack.push(dir);
}
String res = "";
for (String dir : stack) res = "/" + dir + res;
return res.isEmpty() ? "/" : res;
}
}