你需要设计一个能提供下面两个函数的文件系统:
“路径” 是由一个或多个符合下述格式的字符串连接起来形成的:在 /
后跟着一个或多个小写英文字母。
例如 /leetcode
和 /leetcode/problems
都是有效的路径,但空字符串和 /
不是有效的路径。
好了,接下来就请你来实现这两个函数吧!(请参考示例以获得更多信息)
示例 1:
输入:
["FileSystem","create","get"]
[[],["/a",1],["/a"]]
输出:
[null,true,1]
解释:
FileSystem fileSystem = new FileSystem();
fileSystem.create("/a", 1); // 返回 true
fileSystem.get("/a"); // 返回 1
示例 2:
输入:
["FileSystem","create","create","get","create","get"]
[[],["/leet",1],["/leet/code",2],["/leet/code"],["/c/d",1],["/c"]]
输出:
[null,true,true,2,false,-1]
解释:
FileSystem fileSystem = new FileSystem();
fileSystem.create("/leet", 1); // 返回 true
fileSystem.create("/leet/code", 2); // 返回 true
fileSystem.get("/leet/code"); // 返回 2
fileSystem.create("/c/d", 1); // 返回 false 因为父路径 "/c" 不存在。
fileSystem.get("/c"); // 返回 -1 因为该路径不存在。
提示:
对两个函数的调用次数加起来小于等于 10^4
2 <= path.length <= 100
1 <= value <= 10^9
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/design-file-system 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
/
,每个路径最后加个/
,处理起来方便点class FileSystem {
unordered_map<string,int> m;
public:
FileSystem() {
m["/"] = 0;
}
bool createPath(string path, int value) {
if(m.count(path+"/")) return false;
string tmp = path;
while(tmp.back() != '/')
tmp.pop_back();//去除最后一层路径
if(!m.count(tmp)) return false;//前置路径不存在
m[path+"/"] = value;
return true;
}
int get(string path) {
if(m.count(path+'/'))
return m[path+'/'];
return -1;
}
};
408 ms 70 MB