385. Mini Parser
题目描述
Given a nested list of integers represented as a string, implement a parser to deserialize it.
Each element is either an integer, or a list – whose elements may also be integers or other lists.
Note: You may assume that the string is well-formed:
String is non-empty.
String does not contain white spaces.
String contains only digits 0-9, [, - ,, ].
|
|
|
|
题目大意
给定一个字符串表示嵌套列表,实现一个反序列化的解析器。
每个元素代表一个整数或者一个列表。
注意:
- 非空字符。
- 字符串不包含空格。
- 字符串只包含0-9的数字,
[ - ] ,。
示例1:
给定 s = "324"
你应该返回一个包含单个数字324的NestedInteger对象
示例2:
给定s = "[123,[456,[789]]]"
你应该返回一个包含两个元素的嵌套列表的NestedInteger对象:
- 一个数字
324 - 一个包含两个元素的嵌套列表:
- 一个数字
456 - 一个包含一个元素的嵌套列表:
- 一个数字
789
- 一个数字
- 一个数字
解题思路
遍历字符串s,记当前字符为char。
如果char为0-9,则使用value数值。
如果char为-,则将符号变量symbol为-1。
如果char为[,则新建一个NestedInteger对象,并压栈。
如果char为]或者,:
- 如果
value非空,则将value * symbol压栈。- 将栈顶元素弹出,记为
last,如果栈为空,则返回last;如果栈非空,则将last加入栈顶元素的嵌套列表
代码
|
|