leetcode_1166
Solutions
struct Path {
unordered_map<string, Path *> subpaths;
int value = -1;
};
class FileSystem {
public:
Path root;
FileSystem() {
}
vector<string> split(string & path) {
vector<string> paths;
istringstream ss(path);
string p;
while (getline(ss, p, '/'))
paths.push_back(p);
return paths;
}
bool createPath(string path, int value) {
vector<string> paths = split(path);
Path * root = &(this->root);
bool createnew = false;
for (int i = 1; i < paths.size(); i++) {
auto & p = paths[i];
if (!root->subpaths.count(p)) {
if (i != paths.size() - 1)
return false;
createnew = true;
root->subpaths.emplace(p, new Path);
}
root = root->subpaths[p];
}
if (createnew) {
root->value = value;
return true;
}
else return false;
}
int get(string path) {
vector<string> paths = split(path);
Path * root = &(this->root);
for (int i = 1; i < paths.size(); i++) {
auto & p = paths[i];
if (!root->subpaths.count(p))
return -1;
root = root->subpaths[p];
}
return root->value;
}
};
/**
* Your FileSystem object will be instantiated and called as such:
* FileSystem* obj = new FileSystem();
* bool param_1 = obj->createPath(path,value);
* int param_2 = obj->get(path);
*/Last updated