输入参数为字符串型的 n维数组,列表的每一项值为数组 或 int型数字。数组内的数组,每一项值,也可以是数组 或 int型数字。
int型数字,表示数组嵌套的深度。
[[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/
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); } }
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); } }
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); } }