forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.ts
61 lines (53 loc) · 1.41 KB
/
Solution.ts
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
class Trie {
children: Map<string, Trie>;
v: number;
constructor(v: number) {
this.children = new Map<string, Trie>();
this.v = v;
}
insert(w: string, v: number): boolean {
let node: Trie = this;
const ps = w.split('/').slice(1);
for (let i = 0; i < ps.length - 1; ++i) {
const p = ps[i];
if (!node.children.has(p)) {
return false;
}
node = node.children.get(p)!;
}
if (node.children.has(ps[ps.length - 1])) {
return false;
}
node.children.set(ps[ps.length - 1], new Trie(v));
return true;
}
search(w: string): number {
let node: Trie = this;
const ps = w.split('/').slice(1);
for (const p of ps) {
if (!node.children.has(p)) {
return -1;
}
node = node.children.get(p)!;
}
return node.v;
}
}
class FileSystem {
trie: Trie;
constructor() {
this.trie = new Trie(-1);
}
createPath(path: string, value: number): boolean {
return this.trie.insert(path, value);
}
get(path: string): number {
return this.trie.search(path);
}
}
/**
* Your FileSystem object will be instantiated and called as such:
* var obj = new FileSystem()
* var param_1 = obj.createPath(path,value)
* var param_2 = obj.get(path)
*/