congr / world

2 stars 1 forks source link

LeetCode : 588. Design In-Memory File System #464

Open congr opened 5 years ago

congr commented 5 years ago

https://leetcode.com/problems/design-in-memory-file-system/

image image

congr commented 5 years ago
class FileSystem {
    class FileNode {
        TreeMap<String, FileNode> children;
        StringBuilder file;
        String name;

        FileNode(String name) {
            children = new TreeMap<>();
            file = new StringBuilder();
            this.name = name;
        }

        String getContent() {
            return file.toString();
        }

        String getName() {
            return name;
        }

        void addContent(String content) {
            file.append(content);
        }

        boolean isFile() {
            return file.length() > 0;
        }

        List<String> getList() {
            List<String> list = new ArrayList();
            if (isFile()) list.add(this.name);
            else list.addAll(children.keySet());
            return list;
        }
    }

    FileNode root;
    public FileSystem() {
        root = new FileNode("");
    }

    public List<String> ls(String path) {
        return findNode(path).getList();
    }

    public void mkdir(String path) {
        findNode(path);
    }

    public void addContentToFile(String filePath, String content) {
        findNode(filePath).addContent(content);
    }

    public String readContentFromFile(String filePath) {
        return findNode(filePath).getContent();
    }

    FileNode findNode(String path) {
        String[] files = path.split("/");

        FileNode cur = root;
        for (String file : files) {
            if (file.length() == 0) continue;

            cur.children.putIfAbsent(file, new FileNode(file));
            cur = cur.children.get(file);

            if(cur.isFile()) break;
        }

        return cur;
    }
}

/**
 * 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);
 */