242. Design In-Memory File System
Design a data structure that simulates an in-memory file system.
Implement the FileSystem class:
-- FileSystem()
- Initializes the file system.
-- List<String> ls(String path)
- If path points to a file, return a list containing only the file name.
- If path points to a directory, return the list of immediate file and directory names inside it.
- Return the answer in lexicographic order.
-- void mkdir(String path)
- Creates a new directory at the given path.
- The given directory path does not exist.
- If intermediate directories do not exist, create them as well.
-- void addContentToFile(String filePath, String content)
- If filePath does not exist, create the file and store content in it.
- If it already exists, append content to the existing content.
-- String readContentFromFile(String filePath)
- Returns the full content stored in the file at filePath.
Example 1:
Input:
calls = ["FileSystem","mkdir","mkdir","addContentToFile","addContentToFile","ls","readContentFromFile","ls"],
params = [[],["/docs"],["/docs/notes"],["/docs/notes/todo","buy"],["/docs/notes/todo"," milk"],["/docs/notes"],["/docs/notes/todo"],["/"]]
Output: ["","","","","",["todo"],"buy milk",["docs"]]
Explanation:
- Create /docs and /docs/notes.
- Create file /docs/notes/todo with "buy", then append " milk".
- ls("/docs/notes") returns ["todo"].
- Reading the file returns "buy milk".
- ls("/") returns ["docs"].
Example 2:
Input:
calls = ["FileSystem","mkdir","addContentToFile","addContentToFile","mkdir","addContentToFile","ls","ls","readContentFromFile"]
params = [[],["/x/y"],["/x/y/a","A"],["/x/y/b","B"],["/x/z"],["/x/z/c","C"],["/x"],["/x/y/a"],["/x/z/c"]]
Output: ["","","","","","",["y","z"],["a"],"C"]
Explanation:
- /x/y and /x/z are directories.
- Files created: /x/y/a, /x/y/b, /x/z/c.
- ls("/x") lists directories ["y","z"] (sorted).
- ls("/x/y/a") is a file path, so it returns ["a"].
- Reading /x/z/c returns "C".
Now Your Turn!
Pick the correct output for the given inputInput:
calls = ["FileSystem","mkdir","addContentToFile","mkdir","addContentToFile","ls","ls","readContentFromFile"]
params = [[],["/a/b"],["/a/b/file","x"],["/a/c"],["/a/c/file","y"],["/a"],["/a/b/file"],["/a/b/file"]]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
1 <= path.length, filePath.length <= 100
path and filePath are absolute paths:
- begin with '/'
- do not end with '/', except the root path "/"
All directory and file names contain only lowercase English letters
The same names will not exist in the same directory
All operations will be passed valid parameters:
- users will not attempt to list or read a path that does not exist
- the parent directory for the file in addContentToFile will exist
1 <= content.length <= 50
At most 300 calls will be made to ls, mkdir, addContentToFile, and readContentFromFile