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;
}
}