题目地址:
https://leetcode.com/problems/design-file-system/description/
要求设计一个文件系统,可以实现如下操作:
1、给定一个路径
s
s
s和一个值,路径的格式与Linux里的路径一样,题目保证路径不空,不等于根目录,只含英文小写字母。如果该路径已经存在,或其父目录不存在,则返回false;否则创建这个目录,并返回true。
2、返回某个路径
s
s
s对应的值。
用哈希表即可。代码如下:
class FileSystem {
public:
unordered_map<string, int> mp;
FileSystem() {}
bool createPath(string path, int value) {
if (mp.count(path)) return false;
int idx = path.size() - 1;
while (path[idx] != '/') idx--;
string parent = path.substr(0, idx);
if (idx && !mp.count(parent)) return false;
mp[path] = value;
return true;
}
int get(string path) {
auto it = mp.find(path);
return it == mp.end() ? -1 : it->second;
}
};
每个操作时间复杂度 O ( l s ) O(l_s) O(ls),空间 O ( n ) O(n) O(n)。