1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
design-in-memory-file-system.cpp 2.46 KB
一键复制 编辑 原始数据 按行查看 历史
// Time: ls: O(l + klogk), l is the path length, k is the number of entries in the last level directory
// mkdir: O(l)
// addContentToFile: O(l + c), c is the content size
// readContentFromFile: O(l + c)
// Space: O(n + s), n is the number of dir/file nodes, s is the total content size.
class FileSystem {
public:
FileSystem() : root_(new TrieNode()) {
}
vector<string> ls(string path) {
auto curr = getNode(path);
if (curr->isFile) {
return {split(path, '/').back()};
}
vector<string> result;
for (const auto& child : curr->children) {
result.emplace_back(child.first);
}
sort(result.begin(), result.end());
return result;
}
void mkdir(string path) {
auto curr = putNode(path);
curr->isFile = false;
}
void addContentToFile(string filePath, string content) {
auto curr = putNode(filePath);
curr->isFile = true;
curr->content += content;
}
string readContentFromFile(string filePath) {
return getNode(filePath)->content;
}
private:
struct TrieNode {
bool isFile;
unordered_map<string, TrieNode *> children;
string content;
};
TrieNode *root_;
TrieNode *getNode(const string& path) {
vector<string> strs = split(path, '/');
auto curr = root_;
for (const auto& str : strs) {
curr = curr->children[str];
}
return curr;
}
TrieNode *putNode(const string& path) {
vector<string> strs = split(path, '/');
auto curr = root_;
for (const auto& str : strs) {
if (!curr->children.count(str)) {
curr->children[str] = new TrieNode();
}
curr = curr->children[str];
}
return curr;
}
vector<string> split(const string& s, const char delim) {
vector<string> tokens;
stringstream ss(s);
string token;
while (getline(ss, token, delim)) {
if (!token.empty()) {
tokens.emplace_back(token);
}
}
return tokens;
}
};
/**
* Your FileSystem object will be instantiated and called as such:
* FileSystem obj = new FileSystem();
* vector<string> param_1 = obj.ls(path);
* obj.mkdir(path);
* obj.addContentToFile(filePath,content);
* string param_4 = obj.readContentFromFile(filePath);
*/
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助