哈希表
如果没有 parent,可以返回一个特殊字符,表示这个path就是在第一层。然后一开始的时候把这个特殊字符添加到 哈希表里
class FileSystem {
public:
FileSystem() {
hash["H"] = -1;
}
bool createPath(string path, int value) {
if (path.empty() || path[0] != '/' || hash.count(path))
return false;
string parentPath = getParentPath(path);
// Check if parent path exists (or is the root directory) and the path does not already exist
if (!hash.count(parentPath))
return false;
hash[path] = value;
return true;
}
int get(string path) {
if (hash.count(path)) {
return hash[path];
} else {
return -1;
}
}
private:
unordered_map<string, int> hash;
string getParentPath(string path) {
int lastSlash = path.find_last_of('/');
// Special case for the root or first-level directories
if (lastSlash == 0) return "H";
return path.substr(0, lastSlash);
}
};
字典树
Node其实其实就是 file 的class,里面除了 value 还可以 添加 file name,size 各种东西
struct Node {
unordered_map<string, Node*> children;
int value;
Node(int value) : value(value) {}
~Node() {
for (auto& child : children) {
delete child.second;
}
}
};
class FileSystem {
public:
FileSystem() {
root = new Node(0);
}
~FileSystem() {
delete root;
}
bool createPath(string path, int value) {
const vector<string> subpaths = getSubpaths(path);
Node* node = root;
// 检查所有 parent 目录是否存在,不存在 return false
for (int i = 0; i < subpaths.size() - 1; ++i) {
if (!node->children.count(subpaths[i])) {
return false;
}
node = node->children[subpaths[i]];
}
// 检查要建立的file是否存在,存在return false
if (node->children.count(subpaths.back())) {
return false;
}
// 建立file,并且赋值
node->children[subpaths.back()] = new Node(value);
return true;
}
int get(string path) {
const vector<string> subpaths = getSubpaths(path);
Node* node = root;
// 如果 parent 不存在, return -1
for (const string& subpath : subpaths) {
if (!node->children.count(subpath)) {
return -1;
}
node = node->children[subpath];
}
return node->value;
}
private:
Node* root;
// 分割所有subpath,返回一个vector集合
vector<string> getSubpaths(const string& path) {
vector<string> res;
istringstream iss(path);
string subpath;
while (getline(iss, subpath, '/')) {
if (!subpath.empty()) {
res.push_back(subpath);
}
}
return res;
}
};