-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0385-mini-parser.js
More file actions
59 lines (53 loc) · 1.86 KB
/
0385-mini-parser.js
File metadata and controls
59 lines (53 loc) · 1.86 KB
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
/**
* Mini Parser
* Time Complexity: O(N)
* Space Complexity: O(N)
*/
var deserialize = function (s) {
if (s[0] !== '[') {
const finalValue = parseInt(s);
const singleItem = new NestedInteger();
singleItem.setInteger(finalValue);
return singleItem;
}
const objectStack = [];
let currentPosition = 0;
let primaryResult;
while (currentPosition < s.length) {
const currentCharacter = s[currentPosition];
if (currentCharacter === '[') {
const newListInstance = new NestedInteger();
if (objectStack.length > 0) {
const containingList = objectStack[objectStack.length - 1];
containingList.add(newListInstance);
}
objectStack.push(newListInstance);
if (!primaryResult) {
primaryResult = newListInstance;
}
currentPosition++;
} else if (currentCharacter === ']') {
objectStack.pop();
currentPosition++;
} else if (currentCharacter === ',') {
currentPosition++;
} else {
let numberStart = currentPosition;
if (currentCharacter === '-') {
currentPosition++;
}
while (currentPosition < s.length && s[currentPosition] >= '0' && s[currentPosition] <= '9') {
currentPosition++;
}
const numericSegment = s.substring(numberStart, currentPosition);
const parsedInteger = parseInt(numericSegment);
const integerWrapper = new NestedInteger();
integerWrapper.setInteger(parsedInteger);
if (objectStack.length > 0) {
const activeParent = objectStack[objectStack.length - 1];
activeParent.add(integerWrapper);
}
}
}
return primaryResult;
};