|
| 1 | +package design; |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +/** |
| 6 | + * Description: https://leetcode.com/problems/design-in-memory-file-system |
| 7 | + * Difficulty: Hard |
| 8 | + * Time complexity: O(n) |
| 9 | + * Space complexity: O(n) |
| 10 | + */ |
| 11 | +public class DesignInMemoryFileSystem { |
| 12 | + |
| 13 | + private static class FileSystemViaTrie { |
| 14 | + |
| 15 | + private final Node trie; |
| 16 | + |
| 17 | + public FileSystemViaTrie() { |
| 18 | + this.trie = new Node(); |
| 19 | + trie.children.put("", new Node()); |
| 20 | + } |
| 21 | + |
| 22 | + public List<String> ls(String path) { |
| 23 | + // "/".split("/") returns an empty array |
| 24 | + String[] dirs = path.equals("/") ? new String[]{""} : path.split("/"); |
| 25 | + |
| 26 | + Node found = find(dirs); |
| 27 | + if (found == null) return List.of(); |
| 28 | + |
| 29 | + if (found.isFile) { |
| 30 | + // return file name |
| 31 | + return List.of(dirs[dirs.length - 1]); |
| 32 | + } |
| 33 | + |
| 34 | + return found.children.keySet().stream() |
| 35 | + .sorted() |
| 36 | + .toList(); |
| 37 | + } |
| 38 | + |
| 39 | + public void mkdir(String path) { |
| 40 | + String[] dirs = path.split("/"); |
| 41 | + findOrCreate(dirs); |
| 42 | + } |
| 43 | + |
| 44 | + public void addContentToFile(String filePath, String content) { |
| 45 | + String[] dirs = filePath.split("/"); |
| 46 | + |
| 47 | + Node found = findOrCreate(dirs); |
| 48 | + found.isFile = true; |
| 49 | + found.content.append(content); |
| 50 | + } |
| 51 | + |
| 52 | + public String readContentFromFile(String filePath) { |
| 53 | + String[] dirs = filePath.split("/"); |
| 54 | + |
| 55 | + Node found = find(dirs); |
| 56 | + if (found == null) return ""; |
| 57 | + |
| 58 | + return found.content.toString(); |
| 59 | + } |
| 60 | + |
| 61 | + private Node find(String[] path) { |
| 62 | + Node current = trie; |
| 63 | + for (String dir : path) { |
| 64 | + Node child = current.children.get(dir); |
| 65 | + if (child == null) return null; |
| 66 | + current = child; |
| 67 | + } |
| 68 | + |
| 69 | + return current; |
| 70 | + } |
| 71 | + |
| 72 | + private Node findOrCreate(String[] path) { |
| 73 | + Node current = trie; |
| 74 | + for (String dir : path) { |
| 75 | + Node child = current.children.computeIfAbsent(dir, __ -> new Node()); |
| 76 | + current = child; |
| 77 | + } |
| 78 | + |
| 79 | + return current; |
| 80 | + } |
| 81 | + |
| 82 | + private static class Node { |
| 83 | + |
| 84 | + private final Map<String, Node> children; |
| 85 | + private final StringBuilder content; |
| 86 | + private boolean isFile; |
| 87 | + |
| 88 | + public Node() { |
| 89 | + this.children = new HashMap<>(); |
| 90 | + this.content = new StringBuilder(); |
| 91 | + } |
| 92 | + } |
| 93 | + } |
| 94 | +} |
0 commit comments