fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. class FileSystem {
  8. Map<String, Integer> pathMap;
  9. Map<String, Runnable> callbackMap;
  10.  
  11. public FileSystem() {
  12. this.pathMap = new HashMap<>();
  13. this.callbackMap = new HashMap<>();
  14. this.pathMap.put("", 0);
  15. }
  16.  
  17. public boolean create(String path, int value) {
  18. if (pathMap.containsKey(path)) {
  19. return false;
  20. }
  21.  
  22. int lastSlashIndex = path.lastIndexOf("/");
  23. if (!pathMap.containsKey(path.substring(0, lastSlashIndex))) {
  24. return false;
  25. }
  26.  
  27. pathMap.put(path, value);
  28. return true;
  29. }
  30.  
  31. public boolean set(String path, int value) {
  32. if (!pathMap.containsKey(path)) {
  33. return false;
  34. }
  35.  
  36. pathMap.put(path, value);
  37.  
  38. // Trigger callbacks
  39. String curPath = path;
  40. while (curPath.length() > 0) {
  41. if (callbackMap.containsKey(curPath)) {
  42. callbackMap.get(curPath).run();
  43. }
  44. int lastSlashIndex = path.lastIndexOf("/");
  45. curPath = curPath.substring(0, lastSlashIndex);
  46. }
  47.  
  48. return true;
  49. }
  50.  
  51. public Integer get(String path) {
  52. return pathMap.get(path);
  53. }
  54.  
  55. public boolean watch(String path, Runnable callback) {
  56. if (!pathMap.containsKey(path)) {
  57. return false;
  58. }
  59.  
  60. callbackMap.put(path, callback);
  61. return true;
  62. }
  63. }
  64.  
  65. public class Main {
  66. public static void main(String[] args) {
  67. FileSystem fs = new FileSystem();
  68. System.out.println(fs.get("/a")); // null
  69. System.out.println(fs.set("/a", 2)); // false
  70. System.out.println(fs.create("/a", 1)); // true
  71. System.out.println(fs.get("/a")); // 1
  72. System.out.println(fs.create("/a/b", 2)); // true
  73. System.out.println(fs.create("/b/c", 3)); // false
  74. System.out.println(fs.watch("/a/b", new Runnable() {
  75. @Override
  76. public void run() {
  77. System.out.println("callback on /a/b");
  78. System.exit(0);
  79. }
  80. }));
  81. System.out.println(fs.watch("/a", new Runnable() {
  82. @Override
  83. public void run() {
  84. System.out.println("callback on /a");
  85. System.exit(0);
  86. }
  87. }));
  88. System.out.println(fs.set("/a/b", 10)); // trigger 2 callbacks and true
  89. }
  90. }
Success #stdin #stdout 0.08s 2316288KB
stdin
Standard input is empty
stdout
null
false
true
1
true
false
true
true
callback on /a/b