一.题目:
给了一个字符串表示的列表,返回一个NestedInteger形式的列表,其每个元素都是NestedInteger形式的整数对象。
Example 1:
Given s = "324",
You should return a NestedInteger object which contains a single integer 324.
Example 2:
Given s = "[123,[456,[789]]]",
Return a NestedInteger object containing a nested list with 2 elements:
1. An integer containing value 123.
2. A nested list containing two elements:
i. An integer containing value 456.
ii. A nested list with one element:
a. An integer containing value 789.
二.解题思路:
对于这种嵌套的数据结构,我们常用迭代或者递归的方式求解.
对于递归,需要注意的是,递归的出口是字符串为空或者字符串为[ ]或者字符串只包含数字这三种情况.递归的代码如下:
# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
#class NestedInteger(object):
# def __init__(self, value=None):
# """
# If value is not specified, initializes an empty list.
# Otherwise initializes a single integer equal to value.
# """
#
# def isInteger(self):
# """
# @return True if this NestedInteger holds a single integer, rather than a nested list.
# :rtype bool
# """
#
# def add(self, elem):
# """
# Set this NestedInteger to hold a nested list and adds a nested integer elem to it.
# :rtype void
# """
#
# def setInteger(self, value):
# """
# Set this NestedInteger to hold a single integer equal to value.
# :rtype void
# """
#
# 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
# """
#
# 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]
# """
class Solution(object):
def deserialize(self, s):
"""
:type s: str
:rtype: NestedInteger
"""
if not s:
return NestedInteger()
if s[0]!="[":
return NestedInteger(int(s))
if s== "[]":
return NestedInteger()
result = NestedInteger()
cnt = 0
start = 1
for i in range(1,len(s)):
if cnt ==0 and (s[i]=="," or i == len(s)-1):
result.add(self.deserialize(s[start:i]))
start = i+1
elif s[i] == "[":
cnt +=1
elif s[i] == "]":
cnt -=1
return result
还有一种递归的方式,直接使用python的eval函数如下:
def deserialize(self, s):
def nestedInteger(x):
if isinstance(x, int):
return NestedInteger(x)
lst = NestedInteger()
for y in x:
lst.add(nestedInteger(y))
return lst
return nestedInteger(eval(s))
当然这道题也可以用迭代的方法去实现.