File system as graph


  • 0
    H
    import java.util.*;
    public class FileSystem {
    
        class Node {
            int type = 0; //0 file, 1 dir
            String name;
            String filecontent = "";
            HashMap<String, Node> children = new HashMap<>();
            public Node(int type, String name) {
                this.type = type;
                this.name = name;
            }
        }
        Node root = null;
        public FileSystem() {
            root = new Node(1, "/");
        }
    
        public List<String> ls(String path) {
            path = path.substring(1);
            String[] p = path.split("/");
            Node n = root;
            for (String cur : p) {
                if (cur == null || cur.length() == 0) continue;
                n = n.children.get(cur);
            }
            ArrayList<String> res = new ArrayList<>();
            if (n.type == 0) res.add(n.name);
            else {
                for (String name : n.children.keySet()) {
                    res.add(name);
                }
            }
            Collections.sort(res);
            return res;
        }
    
        public void mkdir(String path) {
            path = path.substring(1);
            String[] p = path.split("/");
            Node n = root;
            for (String cur : p) {
                if (!n.children.containsKey(cur)) {
                    n.children.put(cur, new Node(1, cur));
                }
                n = n.children.get(cur);
            }
        }
    
        public void addContentToFile(String filePath, String content) {
            filePath = filePath.substring(1);
            String[] p = filePath.split("/");
            Node n = root;
            for (String cur : p) {
                if (!n.children.containsKey(cur)) {
                    n.children.put(cur, new Node(1, cur));
                }
                n = n.children.get(cur);
            }
            n.type = 0;
            n.filecontent += content;
        }
    
        public String readContentFromFile(String filePath) {
            filePath = filePath.substring(1);
            String[] p = filePath.split("/");
            Node n = root;
            for (String cur : p) {
                n = n.children.get(cur);
            }
            return n.filecontent;
        }
    }
    
    /**
     * Your FileSystem object will be instantiated and called as such:
     * FileSystem obj = new FileSystem();
     * List<String> param_1 = obj.ls(path);
     * obj.mkdir(path);
     * obj.addContentToFile(filePath,content);
     * String param_4 = obj.readContentFromFile(filePath);
     */
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.