-
Notifications
You must be signed in to change notification settings - Fork 0
/
Question222.java
41 lines (35 loc) · 1.23 KB
/
Question222.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
import java.util.Stack;
/**
* Given an absolute pathname that may have . or .. as part of it, return the
* shortest standardized path.
*
* For example, given "/usr/bin/../bin/./scripts/../", return "/usr/bin/".
*/
public class Question222 {
public static void main(String[] args) {
String pathname = "/usr/bin/../bin/./scripts/../";
String standardizedPath = shortestStandardizedPath(pathname);
System.out.println(standardizedPath); // expected output: /usr/bin/
}
public static String shortestStandardizedPath(String path) {
Stack<String> stack = new Stack<>();
String[] components = path.split("/");
for (String component : components) {
if (component.equals(".") || component.isEmpty()) {
continue;
} else if (component.equals("..")) {
if (!stack.isEmpty()) {
stack.pop();
}
} else {
stack.push(component);
}
}
StringBuilder result = new StringBuilder();
for (String dir : stack) {
result.append("/");
result.append(dir);
}
return result.length() > 0 ? result.toString() : "/";
}
}