Leetcode刷题笔记--nested

文章介绍了两个编程问题:ArrayNesting中的深度优先搜索算法用于计算整数数组中最大嵌套层数,MiniParser实现了一个解析嵌套整数字符串的类,利用栈来处理括号和数值。
摘要由CSDN通过智能技术生成

565. Array Nesting

class Solution {
    public int arrayNesting(int[] nums) {
        int ans = 0;
        int len = nums.length;
        for(int i = 0; i < len; i++) {
            if(nums[i]  == -1) {
                continue;
            }
            int next = nums[i];
            int size = 1;
            while(next != i) {
                int temp = nums[next];
                nums[next] = -1;
                size++;
                next = temp;

            }
            ans = Math.max(ans, size);
        }
        return ans;
    }
}

385. Mini Parser

class Solution {
    public NestedInteger deserialize(String s) {
        // 以纯数字开头123 或者也[123,234],
        if(!s.startsWith("[")) {
            return new NestedInteger(Integer.valueOf(s)); 
        }
        Deque<NestedInteger> stack = new ArrayDeque();
        // 不是以纯数字开头的,那么新建一个nestedInteger,加入栈当中
        NestedInteger res = new NestedInteger();
        stack.push(res);
        int left = 1, right = 1; 
        // 用来标记位置,记录下数字,left标记起始位置,right用来遍历,跳过[ 都从1开始
        for(; right < s.length(); right++) { // int right 必须省略
            char ch = s.charAt(right);
            if(ch == '[') {
                NestedInteger cur = new NestedInteger();
                left = right + 1; // 跳过【 确保整数可以substring到
                stack.peek().add(cur); //  嵌套加入,所以顶部元算需要加入新的元素
                stack.push(cur);
            } else if(ch == ']' || ch == ',') {
                //如果是一个空字符串,val没值。所以需要判断保证left小于right
                if(left < right) {
                    Integer val = Integer.valueOf(s.substring(left, right));
                    stack.peek().add(new NestedInteger(val));
                }
                left = right + 1; // 加上left后,最后的right就不一定满足大于left, 必须写,不然 val这行报错nuberformatexception
                if (ch == ']') {
                    stack.pop();
                }
            }
        }
        return res;
    }
}

  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值