-
Notifications
You must be signed in to change notification settings - Fork 14
/
FileSystemPath.java
68 lines (58 loc) · 1.69 KB
/
FileSystemPath.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package by.andd3dfx.common;
import lombok.Getter;
import java.util.ArrayDeque;
import java.util.Deque;
/**
* <pre>
* Write a function that provides change directory (cd) function for an abstract file system.
* Notes:
* Root path is '/'.
* Path separator is '/'.
* Parent directory is addressable as "..".
* Directory names consist only of English alphabet letters (A-Z and a-z).
* The function should support both relative and absolute paths.
* The function will not be passed any invalid paths.
* Do not use built-in path-related functions.
*
* For example:
* Path path = new Path("/a/b/c/d");
* path.cd('../x');
* System.out.println(path.getPath());
*
* should display '/a/b/c/x'.
* </pre>
*
* @see <a href="https://youtu.be/HLoLoIaL--I">Video solution</a>
*/
public class FileSystemPath {
@Getter
private String path;
private Deque<String> deque = new ArrayDeque<>();
public FileSystemPath(String path) {
this.path = path;
String[] directories = path.split("/");
for (String directory : directories) {
deque.addLast(directory);
}
}
public void cd(String newPath) {
path = process(newPath);
}
private String process(String newPath) {
if (newPath.startsWith("/")) {
return newPath;
}
if (newPath.startsWith("./")) {
return path + newPath.substring(1);
}
String[] directories = newPath.split("/");
for (String directory : directories) {
if (directory.equals("..")) {
deque.removeLast();
} else {
deque.addLast(directory);
}
}
return String.join("/", deque);
}
}