-
Notifications
You must be signed in to change notification settings - Fork 251
/
FileSystem.java
101 lines (83 loc) · 2.92 KB
/
FileSystem.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package file_system;
import java.util.*;
import org.junit.*;
import static org.junit.Assert.*;
public class FileSystem {
/*
File System
AirBnB Interview Question
*/
public class Solution {
Map<String, Integer> pathMap;
Map<String, Runnable> callbackMap;
public Solution() {
this.pathMap = new HashMap<>();
this.callbackMap = new HashMap<>();
this.pathMap.put("", 0);
}
public boolean create(String path, int value) {
if (pathMap.containsKey(path)) {
return false;
}
int lastSlashIndex = path.lastIndexOf("/");
if (!pathMap.containsKey(path.substring(0, lastSlashIndex))) {
return false;
}
pathMap.put(path, value);
return true;
}
public boolean set(String path, int value) {
if (!pathMap.containsKey(path)) {
return false;
}
pathMap.put(path, value);
// Trigger callbacks
String curPath = path;
// while (curPath.length() > 0) {
// if (callbackMap.containsKey(curPath)) {
// callbackMap.get(curPath).run();
// }
// int lastSlashIndex = path.lastIndexOf("/");
// curPath = curPath.substring(0, lastSlashIndex);
// }
return true;
}
public Integer get(String path) {
return pathMap.get(path);
}
public boolean watch(String path, Runnable callback) {
if (!pathMap.containsKey(path)) {
return false;
}
callbackMap.put(path, callback);
return true;
}
}
public static class UnitTest {
@Test
public void test1() {
Solution sol = new FileSystem().new Solution();
assertTrue(sol.create("/a",1));
assertEquals(1, (int)sol.get("/a"));
assertTrue(sol.create("/a/b",2));
assertEquals(2, (int)sol.get("/a/b"));
assertTrue(sol.set("/a/b",3));
assertEquals(3, (int)sol.get("/a/b"));
assertFalse(sol.create("/c/d",4));
assertFalse(sol.set("/c/d",4));
sol = new FileSystem().new Solution();
assertTrue(sol.create("/NA",1));
assertTrue(sol.create("/EU",2));
assertEquals(1, (int)sol.get("/NA"));
assertTrue(sol.create("/NA/CA",101));
assertEquals(101, (int)sol.get("/NA/CA"));
assertTrue(sol.set("/NA/CA",102));
assertEquals(102, (int)sol.get("/NA/CA"));
assertTrue(sol.create("/NA/US",101));
assertEquals(101, (int)sol.get("/NA/US"));
assertFalse(sol.create("/NA/CA",101));
assertFalse(sol.create("/SA/MX",103));
assertFalse(sol.set("SA/MX",103));
}
}
}