-
-
Notifications
You must be signed in to change notification settings - Fork 9k
/
Copy pathSolution.java
58 lines (51 loc) · 1.44 KB
/
Solution.java
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
class Trie {
Map<String, Trie> children = new HashMap<>();
int v;
boolean insert(String w, int v) {
Trie node = this;
String[] ps = w.split("/");
for (int i = 1; i < ps.length - 1; ++i) {
String p = ps[i];
if (!node.children.containsKey(p)) {
return false;
}
node = node.children.get(p);
}
if (node.children.containsKey(ps[ps.length - 1])) {
return false;
}
node.children.put(ps[ps.length - 1], new Trie());
node = node.children.get(ps[ps.length - 1]);
node.v = v;
return true;
}
int search(String w) {
Trie node = this;
String[] ps = w.split("/");
for (int i = 1; i < ps.length; ++i) {
String p = ps[i];
if (!node.children.containsKey(p)) {
return -1;
}
node = node.children.get(p);
}
return node.v == 0 ? -1 : node.v;
}
}
class FileSystem {
private Trie trie = new Trie();
public FileSystem() {
}
public boolean createPath(String path, int value) {
return trie.insert(path, value);
}
public int get(String path) {
return trie.search(path);
}
}
/**
* Your FileSystem object will be instantiated and called as such:
* FileSystem obj = new FileSystem();
* boolean param_1 = obj.createPath(path,value);
* int param_2 = obj.get(path);
*/