题目

难度:★★★☆☆

类型:数据结构

方法:考虑周全

给定一个用字符串表示的整数的嵌套列表,实现一个解析它的语法分析器。

列表中的每个元素只可能是整数或整数嵌套列表

提示:你可以假定这些字符串都是格式良好的:

字符串非空

字符串不包含空格

字符串只包含数字0-9、[、-、,、]

示例

示例 1:

给定 s = "324",

你应该返回一个 NestedInteger 对象,其中只包含整数值 324。

示例 2:

给定 s = "[123,[456,[789]]]",

返回一个 NestedInteger 对象包含一个有两个元素的嵌套列表:

一个 integer 包含值 123

一个包含两个元素的嵌套列表:

i. 一个 integer 包含值 456

ii. 一个包含一个元素的嵌套列表

a. 一个 integer 包含值 789

解答

这里主要是需要把情况考虑周到,像这种可以用python中的eval函数实现的功能,一般就需要用递归调用的方式简化编写。

为了使大家有一个直观的认识,这里把题目脚本中缺失的构建这个数据结构的代码补全了,如果你使用pycharm编写,还可以debug查看程序的运行方式。

class NestedInteger:
def __init__(self, value=None):
"""
If value is not specified, initializes an empty list.
Otherwise initializes a single integer equal to value.
"""
self.value = [] if not value else value
def isInteger(self):
"""
@return True if this NestedInteger holds a single integer, rather than a nested list.
:rtype bool
"""
return isinstance(self.value, int)
def add(self, elem):
"""
Set this NestedInteger to hold a nested list and adds a nested integer elem to it.
:rtype void
"""
assert isinstance(self.value, list)
self.value.append(elem)
def setInteger(self, value):
"""
Set this NestedInteger to hold a single integer equal to value.
:rtype void
"""
assert isinstance(value, int)
self.value = value
def getInteger(self):
"""
@return the single integer that this NestedInteger holds, if it holds a single integer
Return None if this NestedInteger holds a nested list
:rtype int
"""
assert isinstance(self.value, int)
return self.value
def getList(self):
"""
@return the nested list that this NestedInteger holds, if it holds a nested list
Return None if this NestedInteger holds a single integer
:rtype List[NestedInteger]
"""
assert isinstance(self.value, list)
return self.value
class Solution(object):
def deserialize(self, s):
"""
:type s: str
:rtype: NestedInteger
"""
def parse(sub_s, i):
"""

解析子串sub_s,这个子串的第一个字符在s中的位置下标是i

"""

if sub_s[i] == "[": # 如果遇到了一个列表的起始标识符

i += 1 # 开始探究列表中的究竟

ret = NestedInteger() # 准备好一个空列表

while i < len(sub_s): # 要在满足下标条件的前提下操作

if sub_s[i] == "]": # 终止符标志着当前这个列表结束了

return ret, i + 1 # 返回构建好的结构体以及新的下标

elif sub_s[i] in "[-0123456789": # 如果在列表中遇到了新的对象(包括列表和正负数)

res, i = parse(sub_s, i) # 递归调用本函数实现解析

ret.add(res) # 解析完成后将解析后的结构体加入到列表当中

else: # 如果遇到逗号,空格或者其他没有什么含义的符号

i += 1 # 指针直接跳过,继续查询

else: # 如果遇到了数字

j = i # 定义指针j用来寻找这个数字的最后一位在哪里

while j < len(sub_s) and sub_s[j] in "-0123456789": # 开始搜索后续的数字

j += 1 # 满足条件时候指针后移

return NestedInteger(int(sub_s[i:j])), j # 寻找完成,将数字添加进入结果

res, _ = parse(s, 0) # 调用函数,实现解析

return res # 返回结果

if __name__ == "__main__":

s = Solution()

res = s.deserialize("[123,[456,[789]]]")

pass

以例子2为例,这个是pycharm中debug时显示的构建的结果。


用pycharm来debug的结果

如有疑问或建议,欢迎评论区留言~