I am trying to solve the below leetcode problem
Design a data structure that simulates an in-memory file system.
Implement the FileSystem class:
FileSystem() Initializes the object of the system. List ls(String path) If path is a file path, returns a list that only contains this file's name. If path is a directory path, returns the list of file and directory names in this directory. The answer should in lexicographic order. void mkdir(String path) Makes a new directory according to the given path. The given directory path does not exist. If the middle directories in the path do not exist, you should create them as well. void addContentToFile(String filePath, String content) If filePath does not exist, creates that file containing given content. If filePath already exists, appends the given content to original content. String readContentFromFile(String filePath) Returns the content in the file at filePath.
Example 1:
Input
["FileSystem", "ls", "mkdir", "addContentToFile", "ls", "readContentFromFile"]
[[], ["/"], ["/a/b/c"], ["/a/b/c/d", "hello"], ["/"], ["/a/b/c/d"]]
Output
[null, [], null, null, ["a"], "hello"]
Explanation
FileSystem fileSystem = new FileSystem();
fileSystem.ls("/"); // return []
fileSystem.mkdir("/a/b/c");
fileSystem.addContentToFile("/a/b/c/d", "hello");
fileSystem.ls("/"); // return ["a"]
fileSystem.readContentFromFile("/a/b/c/d"); // return "hello"
Below is the code I have written for it
class FileSystem:def __init__(self):self.root = {}def ls(self, path: str) -> List[str]:path = path.split('/')node = self.rootfor char in path:if char in node:node = node[char]print(node)node = list(node)print(node)print(path)return sorted(node)def mkdir(self, path: str) -> None:path = path.split('/')node = self.rootfor char in path:if char not in node:node[char] = {}node = node[char]def addContentToFile(self, filePath: str, content: str) -> None:node = self.rootfilePath = filePath.split('/')for char in filePath:if char not in node:node[char] = {}node = node[char]node[content] = '*'def readContentFromFile(self, filePath: str) -> str:node = self.rootfilePath = filePath.split('/')for char in filePath:if char not in node:return "Error"node = node[char]result_list = list(node.keys())return "".join(result_list)
Here is an input I am struggling with
["FileSystem","mkdir","ls","ls","mkdir","ls","ls","addContentToFile","ls","ls","ls"]
[[],["/goowmfn"],["/goowmfn"],["/"],["/z"],["/"],["/"],["/goowmfn/c","shetopcy"],["/z"],["/goowmfn/c"],["/goowmfn"]]
Here is the expected output:
[null,null,[],["goowmfn"],null,["goowmfn","z"],["goowmfn","z"],null,[],["c"],["c"]]
Here is my incorrect output
[null,null,[],["goowmfn"],null,["goowmfn","z"],["goowmfn","z"],null,[],["shetopcy"],["c"]]
I believe the issue comes in when I am not able to return the name of the file for a ls statement but instead return the content of the statement
How do I ensure that when the ls method is run I return the file name or contents in the path not the file contents?
Cheers!