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 62 63 64 65 66 67 68 69 70 71 72
|
class Solution {
private static final NestedInteger SIGN = new NestedInteger(0);
public NestedInteger deserialize(String s) { Deque<NestedInteger> stack = new ArrayDeque<>(); char[] cs = s.toCharArray(); int n = cs.length, i = 0; while (i < n){ if (cs[i] == ',') { ++i; continue; } else if (cs[i] == '-' || (cs[i] >= '0' && cs[i] <= '9')) { int j = cs[i] == '-' ? i + 1 : i; int num = 0; while (j < n && (cs[j] >= '0' && cs[j] <= '9')) num = num * 10 + (cs[j++] - '0'); stack.push(new NestedInteger(cs[i] == '-' ? -num : num)); i = j; } else if(cs[i] == '['){ stack.push(new NestedInteger()); stack.push(SIGN); ++i; } else { List<NestedInteger> list = new ArrayList<>(); while(!stack.isEmpty()){ NestedInteger cur = stack.pop(); if(cur == SIGN) break; list.add(cur); } for(int j = list.size() - 1; j >= 0; --j) stack.peek().add(list.get(j)); ++i; } } return stack.peek(); } }
|