LeetCode 385. Mini Parser

简介: 给定一个用字符串表示的整数的嵌套列表,实现一个解析它的语法分析器。列表中的每个元素只可能是整数或整数嵌套列表

v2-bc3f2db2039e50bb15b5a828b4386191_1440w.jpg

Description



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, [, - ,, ].


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.


描述



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

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


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

字符串非空

字符串不包含空格

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


示例 1:


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


示例 2:


给定 s = "[123,[456,[789]]]",
返回一个 NestedInteger 对象包含一个有两个元素的嵌套列表:
1. 一个 integer 包含值 123
2. 一个包含两个元素的嵌套列表:
    i.  一个 integer 包含值 456
    ii. 一个包含一个元素的嵌套列表
         a. 一个 integer 包含值 789

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/mini-parser

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


思路



  • 使用 json 将字符串转换成为 json 对象。
  • 递归地对 json 对象进行解析。


import json
from collections.abc import Iterable
class Solution:
    def deserialize(self, s: str):
        json_list = json.loads(s)
        def _deserialize(json_list):
            if isinstance(json_list, Iterable):
                nested = NestedInteger()
                for x in json_list:
                    nested.add(_deserialize(x))
                return nested
            else:
                return NestedInteger(json_list)
        return _deserialize(json_list)

源代码文件在 这里


目录
相关文章
|
1月前
|
算法 C++
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题-2
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题
|
1月前
|
算法 C++
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题-1
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题
|
1月前
|
索引
【LeetCode刷题】二分查找:山脉数组的峰顶索引、寻找峰值
【LeetCode刷题】二分查找:山脉数组的峰顶索引、寻找峰值
|
1月前
|
算法
【LeetCode刷题】滑动窗口解决问题:串联所有单词的子串(困难)、最小覆盖子串(困难)
【LeetCode刷题】滑动窗口解决问题:串联所有单词的子串(困难)、最小覆盖子串(困难)
|
1月前
|
算法 容器
【LeetCode刷题】滑动窗口解决问题:水果成篮、找到字符串中所有字母异位词
【LeetCode刷题】滑动窗口解决问题:水果成篮、找到字符串中所有字母异位词
|
1月前
【LeetCode刷题】专题三:二分查找模板
【LeetCode刷题】专题三:二分查找模板
【LeetCode刷题】专题三:二分查找模板
|
1月前
【LeetCode刷题】前缀和解决问题:742.寻找数组的中心下标、238.除自身以外数组的乘积
【LeetCode刷题】前缀和解决问题:742.寻找数组的中心下标、238.除自身以外数组的乘积
|
1月前
【LeetCode刷题】二分查找:寻找旋转排序数组中的最小值、点名
【LeetCode刷题】二分查找:寻找旋转排序数组中的最小值、点名