https://github.com/allaboutjst/airbnb/blob/master/README.md
Write a file system class, which has two functions: create, and get
- create("/a",1)
- get("/a") //get 1
- create("/a/b",2)
- get("/a/b") //get 2
- create("/c/d",1) //Error, because "/c" is not existed
- get("/c") //Error, because "/c" is not existed
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;
}