Java Solution, Graph


  • 0
    C
    public class FileSystem {
            class Node {
                String name;
                Map<String, Node> adj = new HashMap<>();
                String content = null;
    
                public Node(String name) {
                    this.name = name;
                }
            }
    
            Node root;
    
            public FileSystem() {
                root = new Node("/");
            }
    
            public List<String> ls(String path) {
                String[] names = path.substring(1).split("/");
    
                Node p = root;
                for (String name : names) {
                    if(name.equals("")) continue;
                    if (p == null) break;
                    p = p.adj.get(name);
                }
    
                if (p != null) {
                    if(p.content != null) return Collections.singletonList(p.name);
                    else {
                        List<String> res = new ArrayList<>(p.adj.keySet());
                        res.sort(null);
                        return res;
                    }
                }
                else {
                    return new ArrayList<>();
                }
            }
    
            public void mkdir(String path) {
                addContentToFile(path, null);
            }
    
            public void addContentToFile(String filePath, String content) {
                Node p = root;
                String[] names = filePath.substring(1).split("/");
                for (String name : names) {
                    if(name.equals("")) continue;
                    if (!p.adj.containsKey(name)) {
                        Node node = new Node(name);
                        p.adj.put(name, node);
                    }
                    p = p.adj.get(name);
                }
                if(p.content == null) p.content = content;
                else p.content += content;
            }
    
            public String readContentFromFile(String filePath) {
                Node p = root;
                String[] names = filePath.substring(1).split("/");
                for (String name : names) {
                    p = p.adj.get(name);
                }
    
                if (p.content == null) return "";
                else return p.content;
            }
        }
    

Log in to reply
 

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