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
| class Solution { private static final NestedInteger DELIMITER = new NestedInteger(0);
public NestedInteger deserialize(String s) { Stack<NestedInteger> stack = new Stack<>();
int sign = 1;
for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == '-') { sign = -1; }
if (Character.isDigit(c)) { int num = sign * (c - '0'); while (i + 1 < s.length() && Character.isDigit(s.charAt(i + 1))) { num = num * 10 + sign * (s.charAt(i + 1) - '0'); i++; } sign = 1; stack.push(new NestedInteger(num)); } else if (c == '[') { NestedInteger ni = new NestedInteger(); stack.push(ni); stack.push(DELIMITER); } else if (c == ']') { List<NestedInteger> niList = new ArrayList<>(); while (stack.peek() != DELIMITER) { niList.add(stack.pop()); } stack.pop(); NestedInteger root = stack.peek(); for (int j = niList.size() - 1; j >= 0; j--) { root.add(niList.get(j)); } } }
return stack.pop(); } }
|
该题题目阐述不清,并未说明 NestedInteger 不能同时装 num 与 NestedInteger,而是需要将每个 num 包装为 NestedInteger。
References
385. Mini Parser