首页 > 试题广场 >

获取n维数组的最大深度

[编程题]获取n维数组的最大深度
  • 热度指数:4070 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
  • 算法知识视频讲解
输入参数为字符串型的n维数组,数组的每一项值为数组 或 int型数字。请实现一个函数,可以获取列表嵌套列表的最大深度为多少。

输入描述:
输入参数为字符串型的 n维数组,列表的每一项值为数组 或 int型数字。数组内的数组,每一项值,也可以是数组 或 int型数字。


输出描述:
int型数字,表示数组嵌套的深度。
示例1

输入

[[1], [2,3,4], [5,[2,3]], [7], [0,[1,2,3,4],3,5], [1,3], [3,2,4]]

输出

3

说明

n维数组的深度为3
import java.io.*;

public class Main{
    public static void main(String[] args) throws IOException{
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        String str = bf.readLine();
        int count = 0;
        int max = 0;
        for(int i =0;i < str.length();i++){
            if(str.charAt(i) == '['){
                count++;
                if(count > max){
                    max = count;
                }
            }
            if(str.charAt(i) == ']'){
                count--;
            }
        }
        System.out.println(max);
    }
}
leetcode上面的一道题很类似,拿走不谢:https://leetcode-cn.com/problems/remove-outermost-parentheses/
发表于 2020-03-04 19:42:50 回复(0)
Java解法
import java.util.Scanner;
import java.util.Stack;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
        Stack<Character> stack = new Stack<>();
        int maxSize=0;
        for (int i = 0,len =s.length(); i < len ; i++) {
            if (s.charAt(i)=='['){
                stack.push('[');
                maxSize=Math.max(maxSize,stack.size());
            }else if (s.charAt(i)==']')
                stack.pop();
        }
        System.out.println(maxSize);
    }
}


发表于 2020-03-01 16:32:31 回复(0)
Java解答:
import java.util.Scanner;

public class Main {
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        String s = input.nextLine();
        int depth = 0;
        int max = 0;
        for (int i = 0;i<s.length();i++){
            if (s.charAt(i) == '['){
                depth++;
            }else if (s.charAt(i) == ']'){
                depth--;
            }
            if (depth > max)
                max = depth;
        }
        System.out.println(max);
    }
}


发表于 2019-08-06 15:39:19 回复(0)
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String s = br.readLine();
        int count = 0, max = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '[') {
                count++;
                max = (max > count) ? max : count;
            } else if (s.charAt(i) == ']')
                count--;
        }
        System.out.println(max);
    }
}
编辑于 2019-07-15 17:01:56 回复(0)