forked from pxu/Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNestedIntegerParser.java
More file actions
45 lines (40 loc) · 1.27 KB
/
NestedIntegerParser.java
File metadata and controls
45 lines (40 loc) · 1.27 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
public class NestedIntegerParser {
public NestedInteger deserialize(String s) {
if(!s.startsWith("[")) return new NestedInteger(Integer.parseInt(s));
char[] c = s.toCharArray();
Stack<NestedInteger> stack = new Stack<> ();
int i = 0;
while(i < c.length - 1) {
if(c[i] == '[') {
NestedInteger ni = new NestedInteger();
if(stack.empty()) {
stack.push(ni);
}
else {
stack.peek().add(ni);
stack.push(ni);
}
i += 1;
} else if(c[i] == ']') {
stack.pop();
i += 1;
} else if(c[i] == ',') {
i += 1;
continue;
} else {
int sign = 1;
if(c[i] == '-') {
i += 1;
sign = -1;
}
int value = 0;
while(i < c.length - 1 && Character.isDigit(c[i])) {
value = value * 10 + (c[i] - '0');
i += 1;
}
stack.peek().add(new NestedInteger(sign * value));
}
}
return stack.pop();
}
}