You are asked to design a file system that allows you to create new paths and associate them with different values.
The format of a path is one 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 empty string “” and “/“ are not.
Implement the FileSystem class:
bool createPath(string path, int value) Creates a new path and associates a value to it if possible and returns true. Returns false if the path already exists or its parent path doesn’t exist.
int get(string path) Returns the value associated with path or returns -1 if the path doesn’t exist.
structTrie{ unordered_map<string, Trie*> next; int val = -1; Trie(){} boolinsert(queue<string>& q, int v){ if(q.empty()) { if(val == -1) { val = v; returntrue; } elsereturnfalse; } else { auto p = q.front(); q.pop(); if(!next.count(p) and q.empty()) next[p] = newTrie(); if(next.count(p)) return next[p]->insert(q, v); returnfalse; } } intget(queue<string>& q){ if(q.empty()) return val; else { auto p = q.front(); q.pop(); if(!next.count(p)) return-1; return next[p]->get(q); } } }; classFileSystem { Trie* t; public: FileSystem() { t = newTrie(); } queue<string> pathQ(string& path){ if(path.length() <= 1) return {}; queue<string> q; int i = 1, n = path.length(); string s; while(i < n) { if(path[i] == '/') { q.push(s); s = ""; } else s.push_back(path[i]); i++; } q.push(s); return q; } boolcreatePath(string path, int value){ auto q = pathQ(path); return t->insert(q,value); } intget(string path){ auto q = pathQ(path); return t->get(q); } };
/** * 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); */