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
| class FileSystem { private static class Node { Map<String, Node> children; StringBuilder content;
Node(Map<String, Node> _children) { this.children = _children; }
Node(StringBuilder _content) { this.content = _content; } }
private Node root;
public FileSystem() { root = new Node(new TreeMap<>()); }
public List<String> ls(String path) { String[] intermediate = path.split("/"); Node ptr = root; for (int i = 1; i < intermediate.length; i++) { ptr = ptr.children.get(intermediate[i]); } List<String> ans = new ArrayList<>(); if (ptr.content != null) { ans.add(intermediate[intermediate.length - 1]); } else { for (String child : ptr.children.keySet()) { ans.add(child); } } return ans; }
public void mkdir(String path) { Node ptr = root; String[] files = path.split("/"); for (int i = 1; i < files.length; i++) { String file = files[i]; ptr.children.putIfAbsent(file, new Node(new TreeMap<>())); ptr = ptr.children.get(file); } }
public void addContentToFile(String filePath, String content) { Node ptr = root; String[] files = filePath.split("/"); for (int i = 1; i < files.length - 1; i++) { ptr = ptr.children.get(files[i]); } if (ptr.children.containsKey(files[files.length - 1])) { ptr.children.get(files[files.length - 1]).content.append(content); } else { Node newFile = new Node(new StringBuilder()); newFile.content.append(content); ptr.children.put(files[files.length - 1], newFile); } }
public String readContentFromFile(String filePath) { Node ptr = root; String[] files = filePath.split("/"); for (int i = 1; i < files.length - 1; i++) { ptr = ptr.children.get(files[i]); } return ptr.children.get(files[files.length - 1]).content.toString(); } }
|
每个file或者direcory都是一个node, linux中无论文件还是文件夹都认为是file, 那么这里无论file还是dir都抽象为一个node. node的content如果是null, 那么就是文件夹, 否则是文件.
添加文件, ls, mkdir, read就是沿着path走即可.