class FileSystem:
class Dir:
def __init__(self):
self.dirs = {}
self.files = {}
def __init__(self):
self.root = self.Dir()
def ls(self, path: str) -> List[str]:
t = self.root
files = []
if path != "/":
d = path.split("/")
for i in range(1, len(d) - 1):
t = t.dirs[d[i]]
if d[-1] in t.files:
files.append(d[-1])
return files
else:
t = t.dirs[d[-1]]
files.extend(t.dirs.keys())
files.extend(t.files.keys())
files.sort()
return files
def mkdir(self, path: str) -> None:
t = self.root
d = path.split("/")
for i in range(1, len(d)):
if d[i] not in t.dirs:
t.dirs[d[i]] = self.Dir()
t = t.dirs[d[i]]
def addContentToFile(self, filePath: str, content: str) -> None:
t = self.root
d = filePath.split("/")
for i in range(1, len(d) - 1):
t = t.dirs[d[i]]
if d[-1] not in t.files:
t.files[d[-1]] = ""
t.files[d[-1]] += content
def readContentFromFile(self, filePath: str) -> str:
t = self.root
d = filePath.split("/")
for i in range(1, len(d) - 1):
t = t.dirs[d[i]]
return t.files[d[-1]]The time complexity of executing an ls command :
ls, and is the number of entries(files + subdirectories) in the last level directory(in the current input)The time complexity of executing a mkdir command :
mkdirThe time complexity of both addContentToFile and readContentFromFile :
class FileSystem {
class File {
boolean isfile = false;
HashMap < String, File > files = new HashMap < > ();
String content = "";
}
File root;
public FileSystem() {
root = new File();
}
public List < String > ls(String path) {
File t = root;
List < String > files = new ArrayList < > ();
if (!path.equals("/")) {
String[] d = path.split("/");
for (int i = 1; i < d.length; i++) {
t = t.files.get(d[i]);
}
if (t.isfile) {
files.add(d[d.length - 1]);
return files;
}
}
List < String > res_files = new ArrayList < > (t.files.keySet());
Collections.sort(res_files);
return res_files;
}
public void mkdir(String path) {
File t = root;
String[] d = path.split("/");
for (int i = 1; i < d.length; i++) {
if (!t.files.containsKey(d[i]))
t.files.put(d[i], new File());
t = t.files.get(d[i]);
}
}
public void addContentToFile(String filePath, String content) {
File t = root;
String[] d = filePath.split("/");
for (int i = 1; i < d.length - 1; i++) {
t = t.files.get(d[i]);
}
if (!t.files.containsKey(d[d.length - 1]))
t.files.put(d[d.length - 1], new File());
t = t.files.get(d[d.length - 1]);
t.isfile = true;
t.content = t.content + content;
}
public String readContentFromFile(String filePath) {
File t = root;
String[] d = filePath.split("/");
for (int i = 1; i < d.length - 1; i++) {
t = t.files.get(d[i]);
}
return t.files.get(d[d.length - 1]).content;
}
}The time complexity of executing an ls command :
ls, and is the number of entries(files + subdirectories) in the last level directory(in the current input)The time complexity of executing a mkdir command :
mkdirThe time complexity of both addContentToFile and readContentFromFile :