代码
注意addContentToFile 里,别忘记把file 名字传进 node 里去 node->hash[s] = new Node(s);
class Node {
public:
string name;
unordered_map<string, Node*> hash;
bool is_File;
string content;
Node(string name = "", bool is_File = false, string content = "") : name(name), is_File(is_File), content(content) {}
};
class FileSystem {
Node* root;
public:
FileSystem() {
root = new Node();
}
vector<string> getSubPaths(string path) {
vector<string> res;
istringstream iss(path);
string pathPart;
while (getline(iss, pathPart, '/')) {
if (!pathPart.empty()) {
res.push_back(pathPart);
}
}
return res;
}
vector<string> ls(string path) {
Node* node = root;
vector<string> subPaths = getSubPaths(path);
for (const string& s : subPaths) {
node = node->hash[s];
}
if (node->is_File) {
return {node->name};
} else {
vector<string> res;
for (auto& entry : node->hash) {
res.push_back(entry.first);
}
sort(res.begin(), res.end());
return res;
}
}
void mkdir(string path) {
Node* node = root;
vector<string> subPaths = getSubPaths(path);
for (const string& s : subPaths) {
if (!node->hash.count(s)) {
node->hash[s] = new Node(s);
}
node = node->hash[s];
}
}
void addContentToFile(string filePath, string content) {
Node* node = root;
vector<string> subPaths = getSubPaths(filePath);
for (const string& s : subPaths) {
if (node->hash.find(s) == node->hash.end()) {
node->hash[s] = new Node(s);
}
node = node->hash[s];
}
node->is_File = true;
node->content += content; // Append content to the file
}
string readContentFromFile(string filePath) {
Node* node = root;
vector<string> subPaths = getSubPaths(filePath);
for (const string& s : subPaths) {
node = node->hash[s];
}
return node->content;
}
};