-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
53 lines (50 loc) · 1.44 KB
/
index.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
import { NestedInteger } from "./NestedInteger.ts";
const deserializeArray = function (s: string): NestedInteger {
if (s[0] !== "[") {
return new NestedInteger(parseInt(s));
}
const stack = [];
let num = 0;
let negative = false;
for (let i = 0; i < s.length; i++) {
const c = s[i];
if (c === "-") {
negative = true;
} else if (isDigit(c)) {
num = num * 10 + Number(s[i]);
} else if (c === "[") {
stack.push(new NestedInteger());
} else if (c === "," || c === "]") {
if (isDigit(s[i - 1])) {
if (negative) {
num *= -1;
}
stack[stack.length - 1].add(new NestedInteger(num));
}
num = 0;
negative = false;
if (c === "]" && stack.length > 1) {
const ni = stack.pop() as NestedInteger;
stack[stack.length - 1].add(ni);
}
}
}
if (stack.length >= 1) {
return stack.pop() as NestedInteger;
} else {
throw Error("accident");
}
};
export default function deserialize(s: string): NestedInteger {
if (s.startsWith("[")) {
return deserializeArray(s);
} else {
return new NestedInteger(Number(s));
}
}
const nums = Array.from({
length: 10,
}).map((_v, i) => String(i));
const isDigit = (ch: string) => {
return nums.includes(ch);
};