JS解力扣每日一题(三)——385. 迷你语法分析器(2022-4-15)

文章目录

题目

  • 给定一个字符串 s 表示一个整数嵌套列表,实现一个解析它的语法分析器并返回解析的结果 NestedInteger 。
  • 列表中的每个元素只可能是整数或整数嵌套列表

示例1

输入:s = "324",
输出:324
解释:你应该返回一个 NestedInteger 对象,其中只包含整数值 324

示例2

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

我的答案

  • 首先嘛 , 题目要求 , 每次都要返回一个NestedInteger 对象
  • 然后看写题解的地方给了那么多注释 , 一定有用 , 翻译下来对照着看看是什么东西
  • 大概思路就是 把这个字符串转为对象(JSON.stringify(s)) , 封装一个函数(isArray())判断这个对象是不是一个数组(instanceof Array)
    如果不是数组 , 就返回这个对象
    如果是数组 , 遍历这个数组 , 继续判断是否嵌套数组 , 利用递归的思想(递归就是自身调用自身嘛) , 继续调用上面判断是否数组的方法 (isArray())
/**
 * // This is the interface that allows for creating nested lists.
 * // You should not implement it, or speculate about its implementation
 * function NestedInteger() {
 *
 *     Return true if this NestedInteger holds a single integer, rather than a nested list.
 *     @return {boolean}
 *     this.isInteger = function() {
 *         ...
 *     };
 *
 *     Return the single integer that this NestedInteger holds, if it holds a single integer
 *     Return null if this NestedInteger holds a nested list
 *     @return {integer}
 *     this.getInteger = function() {
 *         ...
 *     };
 *
 *     Set this NestedInteger to hold a single integer equal to value.
 *     @return {void}
 *     this.setInteger = function(value) {
 *         ...
 *     };
 *
 *     Set this NestedInteger to hold a nested list and adds a nested integer elem to it.
 *     @return {void}
 *     this.add = function(elem) {
 *         ...
 *     };
 *
 *     Return the nested list that this NestedInteger holds, if it holds a nested list
 *     Return null if this NestedInteger holds a single integer
 *     @return {NestedInteger[]}
 *     this.getList = function() {
 *         ...
 *     };
 * };
 */
/**
 * @param {string} s
 * @return {NestedInteger}
 */
var deserialize = function(s) {
        return isArray(JSON.parse(s))
};

function isArray(val) {
    let nes = new NestedInteger()
    if(!(val instanceof Array)) {
        nes.setInteger(val)
        return nes
    }
    for (i of val) {
        if(i instanceof Array) {
            nse.add(isArray(i))
            return nes
        }
        nes.add(i)
        return nes
        
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值