You are asked to design a file systemthat allows you to create new paths and associate them with different values.
The format of a path isone or more concatenated strings of the form:/ followed by one or more lowercase English letters. For example, “/leetcode"and “/leetcode/problems"are valid paths while an emptystring "" and "/"are not.
Implement theFileSystem class:
bool createPath(string path, int value)Creates a new path and associates a value to it if possible and returns true.Returns falseif the path already exists or its parent path doesn’t exist .
int get(string path)Returns the value associated with path or returns-1if the path doesn’t exist.
string name; int val = -1; unordered_map<string, TrieNode*> m; };
TrieNode* root;
FileSystem() { root = newTrieNode(); }
boolcreatePath(string path, int value){ vector<string> components = getComponents(path); if (components.size() == 0) { returnfalse; } TrieNode* cur = root; int n = components.size(); for (int i = 0; i < n - 1; i++) { string& c = components[i]; if (!cur->m.contains(c)) { returnfalse; } cur = cur->m[c]; } string new_path = components[n - 1]; if (cur->m.contains(new_path)) { returnfalse; } else { cur->m[new_path] = newTrieNode(new_path); cur->m[new_path]->val = value; returntrue; } }
intget(string path){ vector<string> components = getComponents(path); int n = components.size(); TrieNode* cur = root; for (int i = 0; i < n; i++) { string& c = components[i]; if (!cur->m.contains(c)) { return-1; } cur = cur->m[c]; } return cur->val; }
vector<string> getComponents(string path){ int start = 1, end; vector<string> components; while ((end = path.find('/', start)) != string::npos) { components.push_back(path.substr(start, end - start)); start = end + 1; } components.push_back(path.substr(start)); return components; } };
/** * 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); */