题目

类型:栈
image.png

解题思路

分析:
要将子串里面的数字转化为int类型按顺序添加到 NestedInteger 实例里面,因此我们就需要遍历字符串s,如果出现 ‘[’,则表示是一个新的 NestedInteger 实例,需要在栈里构造实例,如果出现‘]’ 或 ‘,’,则需要将栈顶的实例对象添加值【就是‘[’和‘]’ 或 ‘,’之间出现的数字转化为int类型添加进去】,重复上述步骤最后需要将其添加入栈顶的 NestedInteger 实例。最后需返回栈顶的实例。

实现步骤:

如果第一个字符不是‘[’则说明他是一个数字直接转化为int类型添加到NestedInteger里即可
若检测到 - 号标志位置 flag = 1
如果是数字直接计算 【计算前记得判断一下flag是否为1】num
检测到左括号向栈里添加对象
如果检测到‘]’ 或 ‘,’且前一个字符是数字,则直接计算前面连续出现的数字,直接添加到栈顶元素的列表即可
将栈里的 NestedInteger(num) 合并为一个对象列表
按照上述逻辑处理完整个 s,最终栈顶元素即是答案。

image.png

代码

  1. /**
  2. * // This is the interface that allows for creating nested lists.
  3. * // You should not implement it, or speculate about its implementation
  4. * public interface NestedInteger {
  5. * // Constructor initializes an empty nested list.
  6. * public NestedInteger();
  7. *
  8. * // Constructor initializes a single integer.
  9. * public NestedInteger(int value);
  10. *
  11. * // @return true if this NestedInteger holds a single integer, rather than a nested list.
  12. * public boolean isInteger();
  13. *
  14. * // @return the single integer that this NestedInteger holds, if it holds a single integer
  15. * // Return null if this NestedInteger holds a nested list
  16. * public Integer getInteger();
  17. *
  18. * // Set this NestedInteger to hold a single integer.
  19. * public void setInteger(int value);
  20. *
  21. * // Set this NestedInteger to hold a nested list and adds a nested integer to it.
  22. * public void add(NestedInteger ni);
  23. *
  24. * // @return the nested list that this NestedInteger holds, if it holds a nested list
  25. * // Return empty list if this NestedInteger holds a single integer
  26. * public List<NestedInteger> getList();
  27. * }
  28. */
  29. class Solution {
  30. static NestedInteger ph = new NestedInteger(0);
  31. public NestedInteger deserialize(String s) {
  32. Deque<NestedInteger> d = new ArrayDeque<>();
  33. char[] cs = s.toCharArray();
  34. int n = cs.length, i = 0;
  35. while (i < n) {
  36. if (cs[i] == ',' && ++i >= 0) continue;
  37. if (cs[i] == '-' || (cs[i] >= '0' && cs[i] <= '9')) {
  38. int j = cs[i] == '-' ? i + 1 : i, num = 0;
  39. while (j < n && (cs[j] >= '0' && cs[j] <= '9')) num = num * 10 + (cs[j++] - '0');
  40. d.addLast(new NestedInteger(cs[i] == '-' ? -num : num));
  41. i = j;
  42. } else if (cs[i] == '[') {
  43. d.addLast(new NestedInteger());
  44. d.addLast(ph);
  45. i++;
  46. } else {
  47. List<NestedInteger> list = new ArrayList<>();
  48. while (!d.isEmpty()) {
  49. NestedInteger poll = d.pollLast();
  50. if (poll == ph) break;
  51. list.add(poll);
  52. }
  53. for (int j = list.size() - 1; j >= 0; j--) d.peekLast().add(list.get(j));
  54. i++;
  55. }
  56. }
  57. return d.peekLast();
  58. }
  59. }