385. Mini Parserjava
分析:用NI(count,list)來表示NestedInteger,則解析字符串[123,[456,[789]]]
過程以下:git
# 首先將字符串轉化爲字符數組,遍歷每一個字符 [ 壓棧操做 NI(0, null) 123 給棧頂元素設置值 NI(0, NI(123)) , 不處理 [ 壓棧操做 NI(0, NI(123)) | NI(0, null) 456 給棧頂元素設置值 NI(0, NI(123)) | NI(0, 456) , 不處理 [ 壓棧操做 NI(0, NI(123)) | NI(0, NI(456)) | NI(0, null) 789 給棧頂元素設置值 NI(0, NI(123)) | NI(0, NI(456)) | NI(0, NI(789)) ] 出棧並將出棧後的元素添加到棧頂元素NI(0, NI(123)) | NI(0, [NI(456),NI(0, NI(789))]) ] 出棧並將出棧後的元素添加到棧頂元素NI(0, [NI(123), NI(0, [NI(456), NI(0, NI(789))])]) ] 不作處理 # 棧中最後一個元素就是返回結果
Java實現:shell
public NestedInteger deserialize(String s) { if (!s.startsWith("[")) return new NestedInteger(Integer.parseInt(s)); Stack<NestedInteger> stack = new Stack<>(); // 123,[456,[789]] char[] arr = s.toCharArray(); for (int i = 0; i < arr.length; i++) { char ch = arr[i]; if (ch == '[') { stack.push(new NestedInteger()); } else if (ch == ']' & stack.size() > 1) { NestedInteger pop = stack.pop(); stack.peek().add(pop); } else if (Character.isDigit(ch) || ch == '-') { boolean pos = true; if (ch == '-') { pos = false; i++; } int num = 0; while (i < arr.length && Character.isDigit(arr[i])) { num *= 10; num += arr[i++] - '0'; } i--; stack.peek().add(new NestedInteger(pos ? num : -num)); } } return stack.pop(); }