forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
75 lines (66 loc) · 1.6 KB
/
Solution.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
class Trie {
public:
unordered_map<string, Trie*> children;
int v;
Trie(int v) {
this->v = v;
}
bool insert(string& w, int v) {
Trie* node = this;
auto ps = split(w, '/');
for (int i = 1; i < ps.size() - 1; ++i) {
auto p = ps[i];
if (!node->children.count(p)) {
return false;
}
node = node->children[p];
}
if (node->children.count(ps.back())) {
return false;
}
node->children[ps.back()] = new Trie(v);
return true;
}
int search(string& w) {
Trie* node = this;
auto ps = split(w, '/');
for (int i = 1; i < ps.size(); ++i) {
auto p = ps[i];
if (!node->children.count(p)) {
return -1;
}
node = node->children[p];
}
return node->v;
}
private:
vector<string> split(string& s, char delim) {
stringstream ss(s);
string item;
vector<string> res;
while (getline(ss, item, delim)) {
res.emplace_back(item);
}
return res;
}
};
class FileSystem {
public:
FileSystem() {
trie = new Trie(-1);
}
bool createPath(string path, int value) {
return trie->insert(path, value);
}
int get(string path) {
return trie->search(path);
}
private:
Trie* trie;
};
/**
* 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);
*/