Design In-Memory File System
Design an in-memory file system to simulate the following functions:
Example: Input: ["FileSystem","ls","mkdir","addContentToFile","readContentFromFile"] [[],["/"],["/a/b/c"],["/a/b/c/d","hello"],["/a/b/c/d"]] Output: [null,[],null,["a"],"hello"] Explanation: Note:
分析:https://www.cnblogs.com/grandyang/p/6944331.html 这道题比较tricky的地方是ls这个命令,题目中的例子其实不能很好的展示出ls的要求,其对文件和文件夹的处理方式是不同的。由于这里面的文件没有后缀,所以最后一个字符串有可能是文件,也有可能是文件夹。比如a/b/c,那么最后的c有可能是文件夹,也有可能好是文件,如果c是文件夹的话,ls命令要输出文件夹c中的所有文件和文件夹,而当c是文件的话,只需要输出文件c即可。另外需要注意的是在创建文件夹的时候,路径上没有的文件夹都要创建出来,还有就是在给文件添加内容时,路径中没有的文件夹都要创建出来。 1 class File { 2 boolean isFile = false; 3 Map<String,File> children = new HashMap<>(); 4 String content = ""; 5 } 6 7 public class FileSystem { 8 File root = null; 9 10 public FileSystem() { 11 root = new File(); 12 } 13 14 public List<String> ls(String path) { 15 String[] dirs = path.split("/"); 16 File node = root; 17 List<String> result = new ArrayList<>(); 18 String name = ""; 19 for (String dir : dirs) { 20 if (dir.length() == 0) 21 continue; 22 if (!node.children.containsKey(dir)) { 23 return result; 24 } 25 node = node.children.get(dir); 26 name = dir; 27 } 28 29 if (node.isFile) { 30 result.add(name); 31 } else { 32 for (String key : node.children.keySet()) { 33 result.add(key); 34 } 35 } 36 Collections.sort(result); 37 return result; 38 } 39 40 public void mkdir(String path) { 41 String[] dirs = path.split("/"); 42 File node = root; 43 for (String dir : dirs) { 44 if (dir.length() == 0) continue; 45 if (!node.children.containsKey(dir)) { 46 File file = new File(); 47 node.children.put(dir,file); 48 } 49 node = node.children.get(dir); 50 } 51 } 52 53 public void addContentToFile(String filePath,String content) { 54 String[] dirs = filePath.split("/"); 55 File node = root; 56 for (String dir : dirs) { 57 if (dir.length() == 0) continue; 58 if (!node.children.containsKey(dir)) { 59 File file = new File(); 60 node.children.put(dir,file); 61 } 62 node = node.children.get(dir); 63 } 64 node.isFile = true; 65 node.content += content; 66 } 67 68 public String readContentFromFile(String filePath) { 69 String[] dirs = filePath.split("/"); 70 File node = root; 71 for (String dir : dirs) { 72 if (dir.length() == 0) 73 continue; 74 if (!node.children.containsKey(dir)) { 75 File file = new File(); 76 node.children.put(dir,file); 77 } 78 node = node.children.get(dir); 79 } 80 81 return node.content; 82 } 83 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |